Monday, February 16, 2009

[VC++] Getting process name from Process ID

It is easy to obtain the process name from a Process ID.

  • Open the process with Process ID using OpenProcess()
  • Enumerate the loaded modules using EnumProcessModules()
  • Take the first module handle retrieved in the previous step and get the module name using GetModuleBaseName()

See the below code executing the above steps and how to obtain the process name using PID.

HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,
FALSE, dwPID_i );
if( hProcess )
{
char szProcessName[MAX_PATH];
HMODULE hMod;
DWORD dwNeeded;
if( EnumProcessModules( hProcess,
&hMod,
sizeof(HMODULE),
&dwNeeded ))
{
if( GetModuleBaseName( hProcess,
hMod,
szProcessName,
sizeof( szProcessName )))
{
// Show the process name
MessageBox( szProcessName );
}
}
CloseHandle( hProcess );
}
Include psapi.h and link psap.lib for getting these APIs. Above program when slightly modified can be used to obtain all the loaded modules by the process, for this you need to specify a HMODULE array to EnumProcessModules() and loop GetModuleBaseName() for each item of the HMODULE obtained.

No comments: