如何截获消息:"WM_QUIT || WM_DESTROY || WM_CLOSE" WinAPI

How to intercept a message: "WM_QUIT || WM_DESTROY || WM_CLOSE" WinAPI

本文关键字:WM DESTROY CLOSE WinAPI 何截获 QUIT 消息      更新时间:2023-10-16

我将这段代码用于主循环(我的函数):

    while (running)
{
    if(is_close)
    {
        Log().push_log("close", "message close!", logInfo);
        running = active = false;
        break;
    }
    while (PeekMessage(&msg, g_hWnd, 0, 0, PM_REMOVE))
    {
        std::cout << "Wnd: " << msg.message << std::endl;
        if (msg.message == WM_QUIT || msg.message == WM_DESTROY || msg.message == WM_CLOSE)
        {
            MessageBox(0, "Hello, World", "Hello", MB_OK);
            running = false;
        }
        // TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    if (running && active)
        render.DrawObject(g_hDC);
}

好吧,然后我使用WndProc:

LRESULT CALLBACK GLWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    std::cout << "Wnd Proc: " << msg << std::endl;
    return DefWindowProc(hWnd, msg, wParam, lParam);
}

当我尝试在我的函数中获取消息WM_QUITWM_DESTROYWM_CLOSE时,它不起作用。我的函数看不到消息。

如何获取此消息?

PeekMessage 或 GetMessage 将仅返回使用 PostMessage() 发布到消息队列的消息。 这永远不会WM_CLOSE或WM_DESTROY,这些消息使用 SendMessage() 发送,直接传递到窗口过程,不会进入消息队列。 除非你的代码中有PostQuitMessage()调用,否则你不会得到WM_QUIT,否则你不会。

您确实必须为主窗口编写一个窗口过程。 只需处理WM_DESTROY并调用 PostQuitMessage(0) 就足够了。

LRESULT CALLBACK GLWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    if (msg == WM_DESTROY) PostQuitMessage(0);
    return DefWindowProc(hWnd, msg, wParam, lParam);
}

您现在将在游戏循环中获得WM_QUIT。