如何在vba中根据窗口句柄获得进程PID或者线程ID?

api函数GetWindowThreadProcessId可以获得创建窗口的线程ID或者进程ID。

GetWindowThreadProcessId函数的C++语法如下:

DWORD WINAPI GetWindowThreadProcessId(
  _In_      HWND    hWnd,
  _Out_opt_ LPDWORD lpdwProcessId
);

GetWindowThreadProcessId函数的VB声明如下:

Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwprocessid As Long) As Long

其中参数hWnd为窗口的句柄,lpdwProcessId参数为要获得窗口的进程ID,而GetWindowThreadProcessId函数的返回值为创建窗口的线程ID。

以下是获得excel主程序的进程ID和主线程ID的代码:

Public Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwprocessid As Long) As Long
Sub QQ1722187970()
    Dim lHwnd As Long
    '获取当前excel程序的窗口句柄
    lHwnd = Excel.Application.hwnd
    'PID为进程ID
    Dim lPID As Long
    'SID为线程ID
    Dim lSID As Long
    '根据窗户句柄获取进程pid和线程id
    lSID = GetWindowThreadProcessId(lHwnd, lPID)
    MsgBox lPID
    MsgBox lSID
End Sub


 

       

发表评论