按名称获取C进程ID

我试图通过进程名称(例如, notepad.exe )获取进程ID,但StackOverflow上的以前的解决scheme似乎不能正常工作。 这是我试过的:

 DWORD FindProcessId(const char *processname) { HANDLE hProcessSnap; PROCESSENTRY32 pe32; DWORD result = NULL; // Take a snapshot of all processes in the system. hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (INVALID_HANDLE_VALUE == hProcessSnap) return(FALSE); // Retrieve information about the first process, // and exit if unsuccessful if (!Process32First(hProcessSnap, &pe32)) { CloseHandle(hProcessSnap); // clean the snapshot object return(FALSE); } do { if (0 == _stricmp(processname, pe32.szExeFile)) { result = pe32.th32ProcessID; break; } } while (Process32Next(hProcessSnap, &pe32)); CloseHandle(hProcessSnap); return result; } 

我传入“notepad.exe”并确认它正在我的系统上运行,并且该应用程序以pipe理员身份运行,并具有所需的正确权限。 海拔是这样做的:

  if (GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath))) { // Launch itself as administrator. sei.lpVerb = TEXT("runas"); sei.lpFile = szPath; sei.hwnd = NULL; sei.nShow = SW_NORMAL; if (!ShellExecuteEx(&sei)) { MessageBox(NULL, TEXT("The program needs to be elevated to work properly."), APP_TITLE, MB_OK); return -1; } } return 0; 

它永远不会发现进程ID – 每次都返回Null。

这是使用C,而不是C ++。

Solutions Collecting From Web of "按名称获取C进程ID"

解决方法是在获取进程快照后简单地设置pe32.dwSize 。 在这里完成固定代码:

 DWORD FindProcessId(const char *processname) { HANDLE hProcessSnap; PROCESSENTRY32 pe32; DWORD result = NULL; // Take a snapshot of all processes in the system. hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (INVALID_HANDLE_VALUE == hProcessSnap) return(FALSE); pe32.dwSize = sizeof(PROCESSENTRY32); // <----- IMPORTANT // Retrieve information about the first process, // and exit if unsuccessful if (!Process32First(hProcessSnap, &pe32)) { CloseHandle(hProcessSnap); // clean the snapshot object printf("!!! Failed to gather information on system processes! \n"); return(NULL); } do { printf("Checking process %ls\n", pe32.szExeFile); if (0 == strcmp(processname, pe32.szExeFile)) { result = pe32.th32ProcessID; break; } } while (Process32Next(hProcessSnap, &pe32)); CloseHandle(hProcessSnap); return result; }