这是我自己解决的方法,与 XP 兼容,并且可以处理具有多个顶级窗口和多个线程的进程,假设目标进程确实为自己正确处理 WM_QUIT(它当然应该这样做!)
我的目标是来自 C++ 的 Win32 API:
调用Shutdown(filename);
该调用GetProcessID(filename)
以获取进程 ID 然后调用EnumerateWindowThreads(processID)
以获取具有顶级窗口的线程集(我们可以假设它们是进程的“主”线程),并用于PostThreadMessage(..., WM_QUIT, ...)
要求它们中的每一个终止。
WM_QUIT
如果您想调用,可以在发布消息之前打开进程 ID 上的进程句柄GetExitCodeProcess(process_handle, &exit_code)
。只需确保在发布退出之前/期间获取并保持打开一个进程句柄,以确保在完成后您有要查询的内容...
DWORD Shutdown(const TCHAR * executable) {
// assumption: zero id == not currently running...
if (DWORD dwProcessID = GetProcessID(executable)) {
for (DWORD dwThreadID : EnumerateWindowThreads(dwProcessID))
VERIFY(PostThreadMessage(dwThreadID, WM_QUIT, 0, 0));
}
}
// retrieves the (first) process ID of the given executable (or zero if not found)
DWORD GetProcessID(const TCHAR * pszExePathName) {
// attempt to create a snapshot of the currently running processes
Toolbox::AutoHandle::AutoCloseFile snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
if (!snapshot)
throw CWin32APIErrorException(_T(__FUNCTION__), _T("CreateToolhelp32Snapshot"));
PROCESSENTRY32 entry = { sizeof(PROCESSENTRY32), 0 };
for (BOOL bContinue = Process32First(snapshot, &entry); bContinue; bContinue = Process32Next(snapshot, &entry)) {
#if (_WIN32_WINNT >= 0x0600)
static const BOOL isWow64 = IsWow64();
if (isWow64) {
Toolbox::AutoHandle::AutoCloseHandle hProcess(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, entry.th32ProcessID));
DWORD dwSize = countof(entry.szExeFile);
if (!QueryFullProcessImageName(hProcess, 0, entry.szExeFile, dwSize))
//throw CWin32APIErrorException(_T(__FUNCTION__), _T("QueryFullProcessImageName"));
continue;
}
#else
// since we require elevation, go ahead and try to read what we need directly out of the process' virtual memory
if (auto hProcess = Toolbox::AutoHandle::AutoCloseHandle(OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, FALSE, entry.th32ProcessID))) {
if (!GetModuleFileNameEx(hProcess, nullptr, entry.szExeFile, countof(entry.szExeFile)))
//throw CWin32APIErrorException(_T(__FUNCTION__), _T("GetModuleFileNameEx"));
continue;
}
#endif
if (compare_no_case(entry.szExeFile, pszExePathName) == STRCMP_EQUAL)
return entry.th32ProcessID; // FOUND
}
return 0; // NOT FOUND
}
// returns the set of threads that have top level windows for the given process
std::set<DWORD> EnumerateWindowThreads(DWORD dwProcessID) {
if (!dwProcessID)
throw CLabeledException(_T(__FUNCTION__) _T(" invalid process id (0)"));
std::set<DWORD> threads;
for (HWND hwnd = GetTopWindow(NULL); hwnd; hwnd = ::GetNextWindow(hwnd, GW_HWNDNEXT)) {
DWORD dwWindowProcessID;
DWORD dwThreadID = ::GetWindowThreadProcessId(hwnd, &dwWindowProcessID);
if (dwWindowProcessID == dwProcessID)
threads.emplace(dwThreadID);
}
return threads;
}
我很抱歉使用Toolbox::AutoHandle::AutoCloseHandle
我的各种异常类。它们很简单——AutoCloseHandle 是 HANDLE 的 RAII,并且存在异常类是因为我们的代码库早于标准库(而且标准库仍然无法处理 UNICODE 异常)。