开发者

get the full path from a PID using delphi

开发者 https://www.devze.com 2023-01-24 20:13 出处:网络
I need to get the full path from a PID. I\'ve checked this question C++ Windows - How to get process path from its PID

I need to get the full path from a PID.

I've checked this question C++ Windows - How to get process path from its PID and I wrote the following code:

 function GetFullPathFrom开发者_如何学运维PID(PID: DWORD): string;
 var
    hProcess: THandle;
    ModName : Array[0..MAX_PATH + 1] of Char;
 begin
   Result:='';
    hProcess := OpenProcess(PROCESS_ALL_ACCESS,False, PID);
    try
      if hProcess <> 0 then
       if GetModuleFileName(hProcess, ModName, Sizeof(ModName))<>0 then
         Result:=ModName
        else
         ShowMessage(SysErrorMessage(GetLastError));
    finally
     CloseHandle(hProcess);
    end;
 end;

but always return this message:

the specified module could not be found

How can I get the full path from a PID?


You need to use the GetModuleFileNameEx function. From MSDN:

GetModuleFileName Function

Retrieves the fully-qualified path for the file that contains the specified module. The module must have been loaded by the current process.

To locate the file for a module that was loaded by another process, use the GetModuleFileNameEx function.

Sample usage (uses PsAPI):

function GetPathFromPID(const PID: cardinal): string;
var
  hProcess: THandle;
  path: array[0..MAX_PATH - 1] of char;
begin
  hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, false, PID);
  if hProcess <> 0 then
    try
      if GetModuleFileNameEx(hProcess, 0, path, MAX_PATH) = 0 then
        RaiseLastOSError;
      result := path;
    finally
      CloseHandle(hProcess)
    end
  else
    RaiseLastOSError;
end;
0

精彩评论

暂无评论...
验证码 换一张
取 消