Saturday, January 19, 2008

How to get the path and filename of executable file of current process (or running process)?

How to get the path + file name of the current process or the running process?
There are two way to this:

I will illustrate idea in delphi

1. You can call the API function: GetProcessImageFileName

Declare prototype:

interface
function GetProcessImageFileNameA(hProcess: THandle; lpImageFileName: LPSTR;
nSize: DWORD): DWORD; stdcall;
{$EXTERNALSYM GetProcessImageFileNameA}
function GetProcessImageFileNameW(hProcess: THANDLE; lpImageFileName: LPWSTR;
nSize: DWORD): DWORD; stdcall;
{$EXTERNALSYM GetProcessImageFileNameW}
function GetProcessImageFileName(hProcess: THANDLE; lpImageFileName: LPTSTR;
nSize: DWORD): DWORD; stdcall;
{$EXTERNALSYM GetProcessImageFileName}

implementation

function GetProcessImageFileNameA(hProcess: THandle; lpImageFileName: LPSTR;
nSize: DWORD): DWORD; stdcall; external 'Psapi.dll' name 'GetProcessImageFileNameA';
function GetProcessImageFileNameW(hProcess: THANDLE; lpImageFileName: LPWSTR;
nSize: DWORD): DWORD; stdcall; external 'Psapi.dll' name 'GetProcessImageFileNameW';
function GetProcessImageFileName(hProcess: THANDLE; lpImageFileName: LPTSTR;
nSize: DWORD): DWORD; stdcall; external 'Psapi.dll' name 'GetProcessImageFileNameA';


Calling function:

+ GetWindowThreadProcessId(WindowHandle, @processID); ==> get processid
+ processHandle := OpenProcess(PROCESS_TERMINATE or PROCESS_QUERY_INFORMATION,
False, processID); ==> Get process handler
+ GetProcessImageFileName(processHandle , bufferout, lenghtofbufferout)


2. The second way:

Call function GetModuleFileName with first parameter nil
+ GetModuleFileName(0, Buffer, 1024); <== Buffer contain the current path of current process.

No comments:

Google