Search code examples
c++cwindowswinapiwindow

PostMessage not working with posting custom message


I used

PostMessage(NULL,WM_DUCKWND,0,0);

where

#define WM_DUCKWND (WM_USER +4)

to send user-defined msg to all windows in current thread.

DETAILS

this is straight in the main function (DUCKPROC_CLASS_MSG_NAME and DUCKPROC_WINDOW_MSG_NAME are all user-defined macros)

    //create message-only window

    WNDCLASS wndc={};
    wndc.lpfnWndProc = MsgWindowProc;
    wndc.hInstance = hInstance;
    wndc.lpszClassName = DUCKPROC_CLASS_MSG_NAME;
    RegisterClass(&wndc);

    auto hw=CreateWindowEx(NULL, DUCKPROC_CLASS_MSG_NAME, DUCKPROC_WINDOW_MSG_NAME, NULL, 0, 0, 0, 0, HWND_MESSAGE, NULL, hInstance, NULL);


    //post

    PostMessage(NULL,WM_DUCKWND,0,0);


    //message loop

    MSG msg = {};
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

and used WindProc like this

LRESULT CALLBACK MsgWindowProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_DUCKWND:

[BREAKPOINT][BREAKPOINT][BREAKPOINT][BREAKPOINT]

        return 0;
    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

However, the breakpoint isn't triggered as supposed.

How's that wrong?


Solution

  • "all windows in current thread."

    No, that's not correct. HWND==NULL sends the message to the thread message queue. That's the message queue you process with your GetMessage(HWND==NULL) loop.

    DispatchMessage is the function which looks at HWND in msg, and chooses the correct window proc. It does so by looking up the window class of that HWND.

    Since HWND==NULL does not have a window class, it does not have a window proc either, and the message is not dispatched to any window.

    If you want to send WM_DUCKWND(HWND==NULL) to all your windows, you'll have to dispatch it yourself. In this simple example, that's as simple as setting msg.hWnd=hw for msg.message==WM_DUCKWND && msg.hWnd==NULL.

    Side note: it really should be WM_APP+4; the WM_USER range is for messages internal to a window class. The thread message queue is shared by windows, so you shouldn't post WM_USER messages to it.