首页 > 代码库 > C++ 根据进程名找到对应Pid
C++ 根据进程名找到对应Pid
// FileName: FindProcessPid.cpp // Function: Find Pid by ProcessName #include <string.h> #include <stdio.h> #include <Windows.h> #include <tlhelp32.h> //CreateToolhelp32Snapshot #define ArraySize(ptr) (sizeof(ptr) / sizeof(ptr[0])) BOOL FindProcessPid(LPCSTR ProcessName, DWORD& dwPid); int main() { LPCSTR ListApps[]{ "QQ.exe", "chrome.exe" }; // StopMyService(); DWORD dwPid = 0; for (int i = 0; i < ArraySize(ListApps); i++) { if (FindProcessPid(ListApps[i], dwPid)) { printf("[%s] [%d]\n", ListApps[i], dwPid); } else { printf("[%s] [Not Found]\n", ListApps[i]); } } return 0; } BOOL FindProcessPid(LPCSTR ProcessName, DWORD& dwPid) { HANDLE hProcessSnap; PROCESSENTRY32 pe32; // Take a snapshot of all processes in the system. hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnap == INVALID_HANDLE_VALUE) { return(FALSE); } pe32.dwSize = sizeof(PROCESSENTRY32); if (!Process32First(hProcessSnap, &pe32)) { CloseHandle(hProcessSnap); // clean the snapshot object return(FALSE); } BOOL bRet = FALSE; do { if (!strcmp(ProcessName, pe32.szExeFile)) { dwPid = pe32.th32ProcessID; bRet = TRUE; break; } } while (Process32Next(hProcessSnap, &pe32)); CloseHandle(hProcessSnap); return bRet; }
运行效果:
C++ 根据进程名找到对应Pid
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。