Broadcasting user-defined messages

When you broadcast a message (via HWND_BROADCAST) remember that the message you broadcast must have global meaning. I discussed earlier what the various message ranges mean. Notice that only the system-defined range (0..WM_USER-1) and the registered message range (MAXINTATOM .. MAXWORD) have global meaning. The other two ranges have class-specifc or application-specific meanings.

In other words, you can't broadcast a message in the WM_USER range since that message has a different meaning for each window class. Similarly, a message in the WM_APP range has a different meaning for each application.

We ran into this problem in Windows 95. There were programs that decided to broadcast private messages like WM_USER+0x0100, intending them to be delivered to other instances of that program. Of course, when those messages reached some other windows, they interpreted WM_USER+0x0100 as some other private message and either acted funny or crashed.

On the other hand, the programs really wanted the message to reach the windows of other copies of itself, so we couldn't just block the broadcast of the programs would stop working. Progams were relying on the system not trying to stop them from crashing other programs!

The solution was to split the difference. If you broadcast a message that was not safe to broadcast, Windows 95 would send it only to old-style programs. New-style programs (marked as version 4.0 or higher) would not receive the messages.

That way, old programs continued to affect each other as they always did, but new programs followed the new rules.

Moral of the story: When you broadcast a message, make sure it's one that every receiving window will be able to handle.

Comments (5)
  1. Peter Montgomery says:

    That’s why I use "RegisterWindowMessage( )" to create unique messages when I need to send messages globally via "HWND_BROADCAST". Raymond, any insight into the overhead of using "HWND_BROADCAST" versus a targetted handle to send a message to? I assume it’s just one message added to the monster flow of messages every app normally sees. The problem, of course, is that when you assume…

  2. Raymond Chen says:

    Actually you want to avoid doing too much of this, since it wakes up all apps, even dormant ones. For example, if you take notepad, minimize it, and never touch it, none of its code runs and it all eventually gets paged out. But if somebody sits around and keeps broadcasting messages, then notepad’s window procedure will get paged in for the sole purpose of saying, "No, I don’t want that message."

  3. jeffdav says:

    What about calling EnumWindows() and then sending your WM_USER+h directly to your window?

  4. anon says:

    i normally just create a chunk of shared memory (mapped file) to store my window handles when i need to send messages between applications.

  5. Most messages are not safe to broadcast.

Comments are closed.

Skip to main content