Reputation: 231
When I use the SendMessage
function with HWND_BROADCAST
, the application hangs up. There is no response from the application for long time.
Can anyone explain why?
Upvotes: 18
Views: 12385
Reputation: 34148
This will happen when there is an process that has a top level window, but isn't calling GetMessage
or PeekMessage
on the thread that created the window.
For backward compatibility with Windows 3.0, SendMessage
will not return until all of the top level windows in the system have responded to your broadcast. This behavior made sense back before Windows was multithreaded, because SendMessage
, even when sending to other processes would never block.
But beginning with Win32, when you SendMessage
to a window in another process, what actually happens is your thread blocks until the thread in the other process wakes up and handles the message. If that thread is busy, or just not pumping messages, then you wait forever.
For that reason you should always use SendNotifyMessage
or SendMessageTimeout
when you use HWND_BROADCAST
, or are otherwise sending messages to windows owned by other processes.
Upvotes: 27
Reputation: 3446
This is because when SendMessage
is called with HWND_BROADCAST
, it first enumerates all the windows available and then calls SendMessage
for each of those windows. SendMessage
will not return until the window has finished processing the message. If a single window is taking a long time to process the message, the entire call will be delayed.
Upvotes: 5
Reputation: 6894
There is at least one process out there that has a message pump but isn't pumping messages. SendMessage doesn't return until all receivers have processed the message... so it doesn't return. You can try using SendMessageTimeout instead to get around this.
Incidentally, this is why launching a process and waiting on its process handle can be fraught with problems. I describe this on my website here.
Upvotes: 0
Reputation: 3370
There is a SendMessageTimeout which will limit the amount of time your application blocks while waiting for the receiver to accept.
Another workaround is to launch multiple threads and have them deliver multiple messages at once (i.e. to it in parallel). Then if one of the receivers is hung, you don't kill your entire app.
Upvotes: 0