level 11
VB 通过Shell启动word程序,返回PID,使用此PID获取句柄并不是word的句柄(无法进行后续操作)。
用鼠标点击一下word窗口。再用上面同样的代码会获取一个新的句柄,这个句柄是正确可用的。
请问大家如何解决必须鼠标点击word窗体才能获取正确句柄的问题。
2017年11月15日 03点11分
2
level 11
Option Explicit
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As Long, lpdwProcessId As Long) As Long
Private Declare Function GetParent Lib "user32" (ByVal hWnd As Long) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As Long, ByVal lpWindowName As Long) As Long
Private Declare Function GetWindow Lib "user32" (ByVal hWnd As Long, ByVal wCmd As Long) As Long
Const GW_HWNDNEXT = 2
Dim pid As Long
Private Sub Command1_Click()
pid = Shell("C:\Program Files\Microsoft Office\Office14\WINWORD.EXE")
Timer1.Interval = 5000
Timer1.Enabled = True
End Sub
Private Function InstanceToWnd(ByVal target_pid As Long) As Long
Dim test_hwnd As Long
Dim test_pid As Long
Dim test_thread_id As Long
InstanceToWnd = 0
'On Error Resume Next
' 获得首个handle.
test_hwnd = FindWindow(ByVal 0&, ByVal 0&)
' 循环查找直到找到为给定进程ID的窗口句柄
Do While test_hwnd <> 0
'检查窗口句柄是否为顶级窗口
If GetParent(test_hwnd) = 0 Then
' 是顶级窗口
' 取该窗口所属的进程ID
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 Timer1_Timer()
Debug.Print InstanceToWnd(pid)
End Sub
2017年11月15日 03点11分
3