Last active
July 25, 2022 05:56
-
-
Save lyf-is-coding/d25a96bf73ac394a6a5399c6fb89504b to your computer and use it in GitHub Desktop.
C++ Get ProcessID by searching process name in a snapshot of runing processes
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
// https://docs.microsoft.com/en-us/windows/win32/toolhelp/taking-a-snapshot-and-viewing-processes | |
#include <windows.h> // Must include before TlHelp32.h | |
#include <TlHelp32.h> | |
DWORD GetPIDByProcessName(const wchar_t* processName) | |
{ | |
DWORD PID = 0; | |
HANDLE hProcessSnapshot; | |
PROCESSENTRY32 PE32; | |
// Take a snapshot of all processes in the system. | |
hProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); | |
if (hProcessSnapshot == INVALID_HANDLE_VALUE) | |
{ | |
std::cout << "<CreateToolhelp32Snapshot> Invalid handle"; | |
return 0; | |
} | |
// Set the size of the structure before using it. | |
PE32.dwSize = sizeof(PROCESSENTRY32); | |
// Retrieves information about the first process and exit if unsuccessful | |
if (!Process32First(hProcessSnapshot, &PE32)) | |
{ | |
std::cout << "<Process32First> Error " << GetLastError() << '\n'; | |
CloseHandle(hProcessSnapshot); | |
return 0; | |
} | |
// Now walk the snapshot of processes, | |
// and find the right process then get its PID | |
do | |
{ | |
// Returns 0 value indicates that both wchar_t* string are equal | |
if (wcscmp(processName, PE32.szExeFile) == 0) | |
{ | |
PID = PE32.th32ProcessID; | |
break; | |
} | |
} while (Process32Next(hProcessSnapshot, &PE32)); | |
CloseHandle(hProcessSnapshot); | |
return PID; | |
} | |
std::cout << GetPIDByProcessName(L"explorer.exe"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment