user1482045
user1482045

Reputation: 41

What happens to pending messages for a window that has been destroyed?

What happens when a window is destroyed while there are still messages pending for it?

Consider the following scenario:

There are three threads, A, B, and C. Thread C owns a window.

Threads A and B use SendMessage to post messages to the window. The message from A arrives first. While C is processing the message from A, it destroys its window using DestroyWindow.

What happens to the message from thread B? Does the call by thread B to SendMessage return?

How does this work internally?

Upvotes: 4

Views: 1017

Answers (2)

Harry Johnston
Harry Johnston

Reputation: 36348

In principle, what you're proposing to do isn't safe. There's no way for thread C to guarantee that thread B has already sent the message; if the window is destroyed before thread B sends the message, and if the window handle happens to get reused in the meantime, thread B might wind up sending the message to the wrong window, which might be in a different application.

The best practice would be to make sure that all threads have been informed that a particular window handle has become invalid before calling DestroyWindow.

However, practically speaking, the risk of the handle being reused at just the wrong time is very low. If it is not plausible to inform the other threads ahead of time, you are unlikely to get into trouble as a result. I believe that kicsit is right in asserting that the message will not end up waiting in thread C's message queue, although the documentation does not explicitly promise this as far as I can tell.

Upvotes: 1

kicsit
kicsit

Reputation: 503

According to MSDN, DestroyWindow "[...], flushes the thread message queue, [...]". I was not sure whether this meant processing the messages or dumping them, so I tried. It turned out to be the latter: all pending posted messages are removed from the queue and ignored. As for non-queued messages: in my tests the pending SendMessage call returned and set the last error to ERROR_INVALID_PARAMETER - 87 (0x57).

Upvotes: 1

Related Questions