Search code examples
delphidelphi-xe

get the full path from a PID using delphi


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 GetFullPathFromPID(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?


Solution

  • 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;