Get Process ID (PID) from process name (string) – C++ Windows API

Small function to get PID(s) of process(es) having a specific name.

In short, I create a snapshot of existing processes with CreateToolhelp32Snapshot, then I iterate through all of the processes in the snapshot to find the one with the researched name. The return of the function is a vector (a dynamic array) as there can be several processes with the same name.

Here is the function, as a standalone command line program looking for the process(es) ID(s) of process(es) named “notepad.exe” :

#include <iostream>
#include <windows.h>
#include <tlhelp32.h>
#include <vector>

int main(int, char *[]) {
std::vector<DWORD> pids;
std::wstring targetProcessName = L”notepad.exe”;

HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); //all processes

PROCESSENTRY32W entry; //current process
entry.dwSize = sizeof entry;

if (!Process32FirstW(snap, &entry)) { //start with the first in snapshot
return 0;

do {
if (std::wstring(entry.szExeFile) == targetProcessName) {
pids.emplace_back(entry.th32ProcessID); //name matches; add to list
} while (Process32NextW(snap, &entry)); //keep going until end of snapshot

for (int i(0); i < pids.size(); ++i) {
std::cout << pids[i] << std::endl;


1 comment

Leave a Reply

Your email address will not be published. Required fields are marked *