Skip to content

Instantly share code, notes, and snippets.

@baiyanhuang
Created April 5, 2011 02:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baiyanhuang/902894 to your computer and use it in GitHub Desktop.
Save baiyanhuang/902894 to your computer and use it in GitHub Desktop.
Get process handle by its name in Windows
HANDLE GetProcessByName(const TCHAR* szProcessName)
{
if(szProcessName == NULL) return NULL;
CString strProcessName = szProcessName;
DWORD aProcesses[1024], cbNeeded, cProcesses;
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
return NULL;
// Calculate how many process identifiers were returned.
cProcesses = cbNeeded / sizeof(DWORD);
// Print the name and process identifier for each process.
for ( unsigned int i = 0; i < cProcesses; i++ )
{
DWORD dwProcessID = aProcesses[i];
// Get a handle to the process.
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwProcessID );
// Get the process name.
TCHAR szEachProcessName[MAX_PATH];
if (NULL != hProcess)
{
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded))
{
GetModuleBaseName( hProcess, hMod, szEachProcessName, sizeof(szEachProcessName)/sizeof(TCHAR) );
}
}
if(strProcessName.CompareNoCase(szEachProcessName) == 0)
return hProcess;
CloseHandle( hProcess );
}
return NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment