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 ' 通过进程ID获得该进程的窗口句柄 Public 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