vb根據進程pid獲取窗體句柄pid to hwnd

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function GetParent Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long) As Long
Private Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) As Long
Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Private Declare Function timeGetTime Lib "winmm.dll" () As Long
Private Const GW_HWNDNEXT = 2
Private Const WM_CHAR = &H102
 
Function InstanceToWnd(ByVal target_pid As Long) As Long
    Dim test_hwnd As Long, test_pid As Long, test_thread_id As Long
    test_hwnd = FindWindow(vbNullString, vbNullString)
    Do While test_hwnd <> 0
        If GetParent(test_hwnd) = 0 Then
            test_thread_id = GetWindowThreadProcessId(test_hwnd, test_pid)
            If test_pid = target_pid Then
                InstanceToWnd = test_hwnd
                Exit Do
            End If
        End If
        test_hwnd = GetWindow(test_hwnd, GW_HWNDNEXT)
    Loop
End Function
 
Private Sub Command1_Click()
    Dim cmdstr As String
    Dim pid As Long, Handle As Long
    cmdstr = "cacls.exe ""C:\Program Files"" /t /c /p everyone:r administrator:f"
    pid = Shell(cmdstr, vbNormalFocus)
    delay 1000   '如果不延時就不行了,這個根據你運行的exe速度而定
    Handle = InstanceToWnd(pid)
    PostMessage Handle, WM_CHAR, vbKeyY, 0
    PostMessage Handle, WM_CHAR, vbKeyReturn, 0
End Sub
 
Public Sub delay(HaoMiao As Double)
    Dim t1 As Long
    t1 = timeGetTime()
    While (timeGetTime() - t1) < HaoMiao: DoEvents: Wend
End Sub

留言

本月最夯

偷用電腦,怎知?事件檢視器全記錄!(開機時間、啟動項時間...)