VB 6.0 知道某个窗口的句柄,怎么根据这个句柄来查找改窗口的进程名称!

2024-12-03 22:22:50
推荐回答(1个)
回答(1):

一、新建一个模块,复制下面代码:
Option Explicit
Private Declare Function CreateToolhelpSnapshot Lib "kernel32" Alias "CreateToolhelp32Snapshot" (ByVal lFlags As Long, ByVal lProcessID As Long) As Long
Private Declare Function Module32First Lib "kernel32" (ByVal hSnapshot As Long, lppe As MODULEENTRY32) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Declare Function GetWindowThreadProcessId Lib "user32.dll" (ByVal hWnd As Long, lpdwProcessId As Long) As Long
Private Type MODULEENTRY32
dwsize As Long
th32ModuleID As Long
th32ProcessID As Long
GlblcntUsage As Long
ProccntUsage As Long
modBaseAddr As Byte
modBaseSize As Long
hModule As Long
szModule As String * 256
szExePath As String * 1024
End Type

Function GetPrcNameFromWnd(Wnd As Long) As String
Dim lPid As Long, TmpStr As String
Dim hSnapshot As Long
Dim Mode As MODULEENTRY32
Dim mSnapshot As Long
Dim Id As Long
GetWindowThreadProcessId Wnd, Id
hSnapshot = Id '获得进程“快照”的句柄
mSnapshot = CreateToolhelpSnapshot(&H8, hSnapshot)
Mode.dwsize = Len(Mode)
lPid = Module32First(mSnapshot, Mode)
If lPid <> 0 Then '当返回值非零时继续获取下一个进程
TmpStr = Left(Mode.szExePath, InStr(Mode.szExePath, Chr(0)) - 1)
If InStr(TmpStr, ":") > 2 Then TmpStr = Mid(TmpStr, InStr(TmpStr, ":") - 1)
'进程的执行程序的路径
GetPrcNameFromWnd = TmpStr
End If
CloseHandle (mSnapshot) '关闭模块快照句柄
End Function
二、调用举例:
Dim Wnd as long,PrcName as String
Wnd=3700 '窗口句柄
PrcName=GetPrcNameFromWnd(Wnd)