How to list all processes running in Windows with C++ Win32 API

1 Answer

0 votes
#include <windows.h>
#include <tlhelp32.h>
#include <iostream>

void ListProcesses() {
    // Create a snapshot of all processes
    HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hProcessSnap == INVALID_HANDLE_VALUE) {
        std::cerr << "Failed to create process snapshot." << std::endl;
        return;
    }

    PROCESSENTRY32 pe32;
    pe32.dwSize = sizeof(PROCESSENTRY32);

    // Retrieve the first process in the snapshot
    if (Process32First(hProcessSnap, &pe32)) {
        do {
            // Print the process name and ID
            std::wcout << L"Process Name: " << pe32.szExeFile << L", PID: " << pe32.th32ProcessID << "\n";
        } while (Process32Next(hProcessSnap, &pe32)); // Iterate to the next process
    }
    else {
        std::cerr << "Failed to retrieve process information." << std::endl;
    }

    // Close the snapshot handle
    CloseHandle(hProcessSnap);
}

int main() {
    std::cout << "Listing all processes running on Windows:" << "\n\n";

    ListProcesses();

    return 0;
}



/*
run:

Listing all processes running on Windows:

Process Name: [System Process], PID: 0
Process Name: System, PID: 8
Process Name: Registry, PID: 330
Process Name: smss.exe, PID: 786
Process Name: csrss.exe, PID: 112
Process Name: wininit.exe, PID: 900
Process Name: csrss.exe, PID: 908
Process Name: services.exe, PID: 672
Process Name: lsass.exe, PID: 884
Process Name: svchost.exe, PID: 1080
Process Name: fontdrvhost.exe, PID: 120
Process Name: firefox.exe, PID: 6013
Process Name: chrome.exe, PID: 15680
Process Name: NVIDIA Share.exe, PID: 18010
Process Name: msedge.exe, PID: 28013
Process Name: notepad++.exe, PID: 51079

*/

 



answered Mar 29 by avibootz
...