本来想用kernel32中的GetModuleFileName函数来实现的,可惜该函数需要更准确的hModule(因为一个进程中可能包含多个hModule),还得使用EnumProcessModules函数枚举hMos,为了省事,故使用了psapi中的GetModuleFileNameExA函数实现,代码如下:
Option Explicit Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String,ByVal lpWindowName As String) As Long Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As Long,lpdwProcessId As Long) As Long Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long,ByVal bInheritHandle As Long,ByVal dwProcessId As Long) As Long Private Const PROCESS_ALL_ACCESS = &H1F0FFF Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long Private Declare Function GetModuleFileNameExA Lib "psapi.dll" (ByVal hProcess As Long,ByVal hModule As Long,ByVal ModuleName As String,ByVal nSize As Long) As Long Sub Main() Dim strFileName As String Dim hWnd As Long,pId As Long,hProcess As Long strFileName = String(128,Chr(0)) hWnd = FindWindow(vbNullString,"无标题 - 记事本") '以记事本为例 GetWindowThreadProcessId hWnd,pId hProcess = OpenProcess(PROCESS_ALL_ACCESS,pId) strFileName = Left(strFileName,GetModuleFileNameExA(hProcess,strFileName,Len(strFileName))) CloseHandle hProcess MsgBox strFileName End Sub