Registered Messages vs. WM_USER

When sending messages and notification from user-created controls, one has two options to define custom messages. The first is to send a WM_USER message. That is, take the WM_USER constant and add to it a number. For example:

#define SPECIAL_CTRL_CHANGE(WM_USER + 1000)
This allows any window to capture the message or notification using normal ON_COMMAND/ON_NOTIFY macros. However, using WM_USER for normal messages is a mistake. Suppose I created a component called "Special" and another programmer from another side of the galaxy creates a component called "VerySpecial". Both of us could have several messages sent and both would use WM_USER messages. If by any chance both controls will use the same message, a windows program might behave in an unexpected way, since both use the exact same message. This problem exists only when using the ON_COMMAND macro and not ON_NOTIFY, since ON_NOTIFY uses the control id and not just the message code.

Therefore the conclusion is to use WM_USER messages only when sending notification messages and not normal windows messages.

One alternative to using custom Windows messages that are based on the WM_USER message is to register your own Windows messages. The idea behind registered messages is to create a unique Windows message based upon a string. Any window that knows the string can obtain the message code and therefore, respond to the predefined message. This allows several components to create custom messages, and by simply concatenating the component name to the message name, they can be sure that their string is unique, and therefore the message code is unique.

Here's an example of how to add the message handler of a registered message on the client side using the MFC message map.


static const UINT MsgSpecialCtrlChange = ::RegisterWindowMessage(SPECIAL_CTRL_CHANGE);

BEGIN_MESSAGE_MAP(... //{{AFX_MSG_MAP(... . . //}}AFX_MSG_MAP ON_REGISTERED_MESSAGE(MsgSpecialCtrlChange, OnSpecialCtrlChange) END_MESSAGE_MAP()

Where SPECIAL_CTRL_CHANGE is:

#define SPECIAL_CTRL_CHANGE _T("Special_Change")
Another nice advantage that registered message can provide, is the ability to capture the message sent from another application, again by only knowing the string.

The Windows Common Controls use this type of message routing from the DLL to the user application for several messages such as FindOrReplace command in RichEdit control. The intellimouse messages are also sent with registered messages, instead of creating new windows messages for them.

Date Last Updated: March 5, 1999