Visual C++ 6 Unleashed

Visual C++ 6 Unleashed

By MICKEY WILLIAMS and David Bennett

A Common Problem with MFC Message Maps

The MFC message map mechanism is very flexible, and it's well integrated with tools such as MFC AppWizard and ClassWizard. However, a very common mistake made when working with message maps is to attempt to use a message-handling function with the wrong signature. Using a function that has the wrong signature will cause your application's stack to be corrupted—a problem that is very difficult to debug.

Parameters and return values are passed to and from functions on the stack. If the parameter and return value signature don't match the expected values, parts of the stack are overwritten or corrupted. These bugs can be especially difficult to find because they often appear only in Release builds. The fault is masked during Debug builds due to the way the stack frame is managed.

A common mistake is to confuse the signatures on functions used with the ON_COMMAND and ON_MESSAGE macros. Remember that the ON_COMMAND macro expects to use a function with this signature:

afx_msg void OnFileNew();

The ON_MESSAGE macro expects to see a function with this signature:

afx_msg LRESULT OnMyUserMessage(WPARAM wParam, LPARAM lParam);

You might think that the C++ compiler would catch errors like this—but it cannot, due to the use of an old-style C++ cast in the ON_COMMAND and similar message handler macros. Knowledge base article Q195032 (available on your MSDN CD-ROM) shows how you can redefine the message handler macros to be type-safe.

Share ThisShare This

Informit Network