首页 » Visual Basic » vb根据进程pid获取窗体句柄pid to hwnd

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

转发到新浪微博 转发到新浪微博

目前这篇文章还没有评论(Rss)

我要评论
You must be logged in to post a comment.