如何在vba中用QueryFullProcessImageName获取进程的路径名?

如何在vba中用api函数遍历进程? 一文中介绍了遍历进程的方法,但是提取的进程只有进程名称,没有进程的完整路径。

本文介绍使用QueryFullProcessImageName函数获取进程的完整路径的方法。

QueryFullProcessImageName函数的语法如下:

BOOL WINAPI QueryFullProcessImageName(
  _In_    HANDLE hProcess,
  _In_    DWORD  dwFlags,
  _Out_   LPTSTR lpExeName,
  _Inout_ PDWORD lpdwSize
);

其中参数hProcess为要获取的进程句柄,dwFlags参数为指定是用Win32路径格式,还是用系统路径格式,lpExeName参数为存储输出的完整路径的缓存,lpdwSize参数当用做输入参数时,指定缓存的大小,当用做输出参数时,获取实际的完整路径的字符数,不含结尾Null字符。

以下是获取当前进程的完整路径的代码:

Public Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Public Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Public Declare Function GetCurrentProcessId Lib "kernel32" () As Long
Declare Function QueryFullProcessImageName Lib "kernel32" Alias "QueryFullProcessImageNameA" (ByVal hProcess As Long, ByVal dwFlags As Long, _
ByVal lpExeName As String, lpdwSize As Long) As Boolean
'定义一个进程的访问权限常量,表示可以具有所有权限
Public Const PROCESS_ALL_ACCESS = &H1F0FFF
Public Const PROCESS_NAME_NATIVE = &H1
Sub QQ1722187970()
    Dim lPid As Long
    Dim sFullPath As String
    Dim lLen As Long
    '定义一个存储进程完整路径的变量,先填充空格
    sFullPath = Space(1024)
    '先设置一个缓冲大小
    lLen = 1024
    lPid = GetCurrentProcessId
    '进程句柄变量
    Dim hProcess As Long
    hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, pid)
    Debug.Print hProcess
    QueryFullProcessImageName hProcess, 0, sFullPath, lLen
    '获取实际的进程完整路径
    sFullPath = Left(sFullPath, lLen)
    Debug.Print sFullPath, Len(sFullPath)
    '关闭进程句柄
    CloseHandle hProcess
End Sub
       

发表评论