【发布时间】:2023-03-17 18:00:01
【问题描述】:
我正在使用下面的代码来获取给定进程的文件路径和名称。我只是将 ProcessID 传递给函数 ExePathFromProcID ,它应该返回完整路径。它将硬盘驱动器枚举为设备而不是使用驱动器号,但这不是我的抱怨。查看我的代码,然后在下面查看我的投诉。
Public Declare Function OpenProcess Lib "kernel32" ( _
ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, _
ByVal dwProcessId As Long) As Long
Public Declare Function GetProcessImageFileName Lib "psapi.dll" Alias "GetProcessImageFileNameA" _
(ByVal hProcess As Long, _
ByVal lpImageFileName As String, _
ByVal nSize As Long) As Long
Public Declare Function CloseHandle Lib "kernel32" ( _
ByVal hObject As Long) As Long
Private Function ExePathFromProcID(idProc As Long) As String
Const MAX_PATH = 260
Const PROCESS_QUERY_INFORMATION = &H400
Const PROCESS_VM_READ = &H10
Dim sBuf As String
Dim sChar As Long, l As Long, hProcess As Long
sBuf = String$(MAX_PATH, Chr$(0))
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION Or PROCESS_VM_READ, 0, idProc)
If hProcess Then
sChar = GetProcessImageFileName(hProcess, sBuf, MAX_PATH)
If sChar Then
sBuf = Left$(sBuf, sChar)
ExePathFromProcID = sBuf
Debug.Print sBuf
End If
CloseHandle hProcess
End If
End Function
我的抱怨是,只要首先检索到较长的路径,当返回较短的路径时,较长的流程路径的部分仍然会显示。这是一个例子:
第一次调用(正确结果):
\Device\HarddiskVolume2\Program Files\Portable Apps\Notepad++ Portable\App\Notepad++\notepad++.exe
第二次通话(意外结果):
\Device\HarddiskVolume2\Program Files\Microsoft Office\Office12\MSACCESS.EXE tepad++\notepad++.exe
注意到第二次调用结果末尾的“tepad++\notepad++.exe”了吗?不要被它落在第二行的事实所迷惑。它都是同一个字符串的一部分,并且在第二次调用这个函数时全部返回。
知道为什么我的函数会返回这个吗?看起来这是一个全局字符串变量没有被清除的问题,但我使用的代码几乎和我发布的一样。没有全局变量。
【问题讨论】:
-
你在什么环境下测试?您是否遍历了返回字符串以检查将新信息与剩余旧信息分开的空字符?