Get Process Name via QueryFullProcessImageName - Delphi

DarkCoderSc personal avatar
DarkCoderSc

Jean-Pierre LESUEUR

uses
  System.SysUtils, Winapi.Windows;

// ...

const PROCESS_QUERY_LIMITED_INFORMATION = $00001000;

// ...

function QueryFullProcessImageNameW(
  hProcess   : THandle;
  dwFlags    : DWORD;
  lpExeName  : PWideChar;
  var dwSize : DWORD
): BOOL; stdcall; external kernel32 name 'QueryFullProcessImageNameW';

// ...

function GetProcessName_QueryFullProcessImageName(const AProcessID : Cardinal) : String;
begin
  result := 'Unknown';
  ///

  if (TOSVersion.Major < 6) then
    raise Exception.Create('Method not compatible with current OS Version. Requires >= 6');
  ///


  var hProc := OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, AProcessID);
  if hProc = 0 then
    raise EWindowsException.Create('OpenProcess');
  try
    var ALength := DWORD(MAX_PATH * 2);

    // Alternative to GetMem
    SetLength(result, ALength);

    if NOT QueryFullProcessImageNameW(hProc, 0, @result[1], ALength) then
      raise EWindowsException.Create('QueryFullProcessImageNameW');

    SetLength(result, ALength);
  finally
    CloseHandle(hProc);
  end;
end;

// ...

writeln(GetProcessName_QueryFullProcessImageName(GetCurrentProcessId));

Implemented By Technique


Created

April 14, 2025

Last Revised

April 14, 2025