Created
April 5, 2011 02:06
-
-
Save hpcx82/902894 to your computer and use it in GitHub Desktop.
Get process handle by its name in Windows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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