Created
November 9, 2022 15:53
-
-
Save richardiwnl/ed50d2972b5ef9b9b9dca89edd023dad to your computer and use it in GitHub Desktop.
Searches for a process ID by its name
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
#include <iostream> | |
#include <Windows.h> | |
#include <TlHelp32.h> | |
DWORD findProcessID(const std::wstring_view processName); | |
int main() | |
{ | |
std::cout << findProcessID(L"notepad.exe") << '\n'; | |
return 0; | |
} | |
DWORD findProcessID(const std::wstring_view processName) | |
{ | |
PROCESSENTRY32 processInfo{}; | |
processInfo.dwSize = sizeof(processInfo); | |
HANDLE procSnapshot{ CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL) }; | |
if (procSnapshot == INVALID_HANDLE_VALUE) return 0; | |
Process32First(procSnapshot, &processInfo); | |
if (!processName.compare(processInfo.szExeFile)) | |
{ | |
CloseHandle(procSnapshot); | |
return processInfo.th32ProcessID; | |
} | |
while (Process32Next(procSnapshot, &processInfo)) | |
{ | |
if (!processName.compare(processInfo.szExeFile)) | |
{ | |
CloseHandle(procSnapshot); | |
return processInfo.th32ProcessID; | |
} | |
} | |
CloseHandle(procSnapshot); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment