Created
January 22, 2019 07:17
-
-
Save peta909/c8ff05c3bca0ecf9762cb3883ec8b000 to your computer and use it in GitHub Desktop.
Function to locate PID based on given process name in string
This file contains 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
int LocateProcess(wchar_t* proc) | |
{ | |
// Need to add #include <tlhelp32.h> for PROCESS* definitions | |
HANDLE hProcessSnap; | |
HANDLE hProcess; | |
PROCESSENTRY32 pe32; | |
DWORD dwPriorityClass; | |
int FoundPID; | |
// Take a snapshot of all processes in the system. | |
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); | |
if (hProcessSnap == INVALID_HANDLE_VALUE) | |
{ | |
printf("CreateToolhelp32Snapshot (of processes)"); | |
return(FALSE); | |
} | |
// Set the size of the structure before using it. | |
pe32.dwSize = sizeof(PROCESSENTRY32); | |
// Retrieve information about the first process, | |
// and exit if unsuccessful | |
if (!Process32First(hProcessSnap, &pe32)) | |
{ | |
printf("Process32First"); // show cause of failure | |
CloseHandle(hProcessSnap); // clean the snapshot object | |
return(FALSE); | |
} | |
// Now walk the snapshot of processes, and | |
// display information about each process in turn | |
do | |
{ | |
if (wcscmp(pe32.szExeFile, proc) == 0) | |
{ | |
//_tprintf(TEXT("\n\n=====================================================")); | |
//_tprintf(TEXT("\nPROCESS NAME: %s"), pe32.szExeFile); | |
//_tprintf(TEXT("\n-------------------------------------------------------")); | |
// Retrieve the priority class. | |
dwPriorityClass = 0; | |
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID); | |
if (hProcess == NULL) | |
printf("OpenProcess"); | |
else | |
{ | |
dwPriorityClass = GetPriorityClass(hProcess); | |
if (!dwPriorityClass) | |
printf("GetPriorityClass"); | |
CloseHandle(hProcess); | |
} | |
FoundPID = pe32.th32ProcessID; | |
} | |
} while (Process32Next(hProcessSnap, &pe32)); | |
CloseHandle(hProcessSnap); | |
return(FoundPID); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment