November 25th, 2024

How can I know when a window has processed a message that I posted to it?

A customer was writing diagnostic code to monitor another application. They found that under certain conditions (which they can detect by other means), the program would stop responding to incoming posted messages, though it would respond to incoming sent messages.¹ Is there version of Post­Message that puts the message in the message queue and either waits for the message to be retrieved (like Send­Message) or calls you back when the retrieval occurs (like Send­Message­Callback)?

No, there is no such version. When a message is posted, it is placed in destination queue, and that’s the end of it. There is no further tracking of the message.

If you can change the target program, you can post it a custom message like WM_HEARTBEAT and implement the handler for that message by posting an acknowledgement back.

// Monitoring program posts a heartbeat
PostMessage(hwndAppBeingMonitored, WM_HEARTBEAT,
    (WPARAM)hwndMonitor,
    MAKELPARAM(replyMessage, replyMessageData));

// Program being monitored replies with a heartbeat
case WM_HEARTBEAT:
    PostMessage((HWND)wParam, LOWORD(lParam),
                HIWORD(lParam), 0);

If you cannot make changes to the app being monitored, you could install a WH_GET­MESSAGE hook onto the UI thread of the app you are monitoring, post the window a harmless message like WM_NULL, and have your hook respond when it sees that message.

Another option is to post a harmless message that has some observable effect, like WM_CONTEXT­MENU and then use accessibility or UI Automation to detect when the menu appears. (You could also use accessibility or UI Automation to dismiss the menu.)

¹ This can happen if the thread is inside its own Send­Message call to another thread. While waiting for Send­Message to complete, the thread can process inbound sent messages, but inbound posted messages go into the queue and are not processed until the thread calls Get­Message or Peek­Message.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments