|Date:||June 12, 2006 / year-entry #196|
|Summary:||Occasionally I catch people doing things like broadcasting a WM_COMMAND message to all top-level windows. This is one of those things that is so obviously wrong I don't see how people even thought to try it in the first place. Suppose you broadcast the message SendMessage(HWND_BROADCAST, WM_COMMAND, 100, 0); What happens? Every top-level window receives...|
Occasionally I catch people doing things like broadcasting
Suppose you broadcast the message
SendMessage(HWND_BROADCAST, WM_COMMAND, 100, 0);
Every top-level window receives the message with the same parameters, and every top-level window starts interpreting those parameters in their own idiosyncratic way. As you know (since you've written them yourself), each window procedure defines its own menu items and child windows and there is no guarantee that command 100 will mean the same thing to each window. A dialog box with the template
#define IDC_USEDEFAULT 100 ... AUTORADIOBUTTON "Use &default color", IDC_USEDEFAULT, 14, 38, 68, 10, WS_TABSTOP
would interpret the message as
Depending on how the dialog procedure is written,
it might try to send a message back to the button control
(and fail since you passed
Another dialog box might have the template
#define IDC_CHANGE 100 ... PUSHBUTTON "C&hange", IDC_CHANGE, 88, 95, 50, 14
This dialog procedure would interpret the message as
The reaction would probably be to apply the changes that were pending in the dialog.
Meanwhile, another window might have a menu that goes like this:
#define IDC_REFRESH 100 ... MENUITEM "&Refresh", IDC_REFRESH
It is going to interpret the message as the user having selected "Refresh" from the window menu.
Not only is the command code invalid for a menu item, the window might be in a state where the program had disabled the "Refresh" option. Yet you sent the window a message as if to say that the user selected it anyway, which is impossible. Congratulations, you just presented the program with an impossible situation and it very well may crash as a result. For example, the program may have disabled the "Refresh" option since there is no current object to refresh. When you send it the "Refresh" command, it will try to refresh the current object and crash with a null pointer error.
Obviously, then, you cannot broadcast the
The same logic applies to nearly all of the standard Windows messages. The ones that are actually designed to be broadcast are as follows:
If you try to broadcast a message in the
The same caution applies, using the same logic, to
sending messages without universal meaning to windows
whose window class you do not have an interface contract with.
For example, I'll see people sending the
Remember, then, that when you send a message to a window, you need to be sure that the window will interpret it in the manner you intend.
<-- Back to Old New Thing Archive Index