简体   繁体   中英

Handling window messages in wndproc vs MSG, what's the difference?

I noticed that MSG from winuser.h (which is typedef'd to tagMSG) contains all the parameters from wndproc callback. I was wondering if there's any real difference handling messages in wndproc vs handling the outside of wndproc by using MSG, along with the different use cases between the two

Basically something like the following

LRESULT WinApp::WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{   
   switch (uMsg)
   {
    case WM_KEYDOWN:
        if (wParam == VK_ESCAPE)
        {
            DestroyWindow(hwnd);
        }
        break;
    default:
        return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
}

vs

MSG msg;
if ((PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
    switch (msg.message)
    {
    case WM_KEYDOWN:
        if (wParam == VK_ESCAPE)
            {
            DestroyWindow(hwnd);
            }
        break;
    default:
        return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
}

The difference is that using the normal message loop will handle cases involving multiple window classes, each with its own WndProc. What you show will only work if there is only going to be one set of message handlers for all windows (including popup menus).

Each window is associated with a WindowProc function. Both queued and non-queued messages that are dispatched to a window will arrive in its WindowProc. This is the preferred place to process messages that are specific to each window.

MSG is used when retrieving queued messages from a thread's message queue, before dispatching the messages to their target windows (see DispatchMessage() ). Processing messages directly in the message loop is the preferred way to handle messages that are specific to a thread but not necessarily to a specific window.

Basically it's the same, in terms of code processing and execution.

But, the main difference goes from the SendMessage function's family:

The SendMessage function calls the window procedure for the specified window...

Generally speaking, in Windows world each window has its own window's procedure, that can be called outside of the thread's message loop this window belongs to. As opposed to the PostMessage function, that:

Places (posts) a message in the message queue associated with the thread that created the specified window

So now it's clear, that messages might be handled in the main message loop, but in this case you are able to handle only the thread 's messages. But you lose the ability to handle messages that was sent directly to your WndProc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM