KostyaKulakov
KostyaKulakov

Reputation: 25

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

I use this code for the main loop (my function):

    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);
}

Well, then I use 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);
}

When I'm trying to get the message WM_QUIT, WM_DESTROY, or WM_CLOSE in my function, it does not work. My function does not see messages.

How can I get this message?

Upvotes: 2

Views: 4738

Answers (1)

Hans Passant
Hans Passant

Reputation: 941217

PeekMessage or GetMessage will only return messages that were posted to the message queue with PostMessage(). That will never be WM_CLOSE or WM_DESTROY, those messages are sent with SendMessage(), directly delivered to the window procedure and don't go in the message queue. You won't get WM_QUIT unless you've got a PostQuitMessage() call in your code, you don't.

You really do have to write a window procedure for your main window. Simply handling WM_DESTROY and calling PostQuitMessage(0) should be enough.

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

You'll now get WM_QUIT in your game loop.

Upvotes: 11

Related Questions