C++——获取进程名和进程ID
转载来自:https://www.cnblogs.com/LCCRNblog/p/4652374.html
#include <iostream> #include <string> #include <map> #include <windows.h> #include <TlHelp32.h> using namespace std; bool traverseProcesses(map<string, int>& _nameID) { PROCESSENTRY32 pe32; pe32.dwSize = sizeof(pe32); HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);//获取进程快照 if(hProcessSnap == INVALID_HANDLE_VALUE) { cout << "CreateToolhelp32Snapshot Error!" << endl;; return false; } BOOL bResult =Process32First(hProcessSnap, &pe32); int num(0); while(bResult) { //string name = string(pe32.szExeFile); char temp[300]; WideCharToMultiByte(CP_ACP, 0, pe32.szExeFile, -1, temp, sizeof(temp), NULL, NULL); string name = string(temp); int id = pe32.th32ProcessID; cout << "[" << ++num << "] : " <<"Process Name:" << name << " " << "ProcessID:" << id<< endl; _nameID.insert(pair<string, int>(name, id)); //字典存储 bResult = Process32Next(hProcessSnap,&pe32); } CloseHandle(hProcessSnap); return true; } int main() { map<string, int> _nameID; if (!traverseProcesses(_nameID)) { cout << "Start Process Error!" << endl; } return 0; }