如何(最好)将 WM_QUIT 发布到正在运行的进程?

Mor*_*hai 4 c++ windows winapi shutdown process

目标:关闭Windows下正在运行的32位GUI进程

  • 我可以访问可执行路径名。
  • 该软件可能有多个副本正在运行,但只有一个副本是从唯一的可执行路径名启动的。
  • 由于可以运行该可执行文件的多个实例,因此只需查看顶层窗口就需要区分哪个可执行文件路径名实际上负责该窗口...

可能的方法:

枚举进程和线程,然后使用PostThreadMessage(thread, WM_QUIT, 0, 0)

  • 这是有道理的,但我担心用什么技术来区分“主线程”

这种方法有一些例子:

枚举顶级窗口,获取进程标识,并将消息发送到窗口:

其他想法:

  • 我的目标应用程序是多语言的 - 所以查看顶级窗口的名称似乎也不正确......因为我不知道它会说什么(它也是根据用户的设置动态的)。

基本上,我想要的是一种可靠的方法来告诉我的应用程序 - 从特定可执行路径名启动的特定实例(参数并不重要 - 但路径很重要),关闭。

有没有更好的方法:

  • 也许创建一个命名信号量来发出信号?
  • 已注册 Windows 消息广播(路径名作为 ATOM 传递)?
  • 还有其他IPC机制吗?

预先感谢您提供的任何想法...

Mor*_*hai 5

这是我自己解决的方法,与 XP 兼容,并且可以处理具有多个顶级窗口和多个线程的进程,假设目标进程确实正确地为自己处理 WM_QUIT (它当然应该!)

我的目标是 C++ 的 Win32 API:

callShutdown(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;
}
Run Code Online (Sandbox Code Playgroud)

我对使用Toolbox::AutoHandle::AutoCloseHandle和我的各种异常类表示歉意。它们很简单 - AutoCloseHandle 是 HANDLE 的 RAII,异常类的存在是因为我们的代码库早于标准库(而且标准库无论如何仍然无法处理 UNICODE 异常)。