Discussion: Message-Handler Functions

Once you've grasped the principles of handling Windows messages in your program, the process is straightforward. This discussion reviews the process. Later sections present the message-handler functions.

Provide Message-Handler Functions and Message-Map Entries

Your message-handler functions are declared as member functions of your window class.

For each message-handler function, provide a corresponding macro entry in the message map for your window class.

If you write programs with multiple windows, each different kind of window requires its own set of message-handler functions and corresponding message-map.

Phone Book uses only one kind of window (other than dialogs). Class
CMainWindow declares a constructor and many message handlers. Its message
map, which you implemented in VIEW.CPP, contains matching entries.

Follow the Rules for Naming Message-Handler Functions

As discussed in Chapter 2, the message-map mechanism used in the Microsoft Foundation Class Library to connect Windows messages with your message handlers has certain requirements for names.

Handler functions for WM_COMMAND messages, used primarily for menus and accelerator keys, can be named anything you like, but usually their names reflect their functions. Menu handlers, for example, are typically named after the menu command they handle. These handlers take no arguments and return no values.

In the message map, use the ON_COMMAND macro for each of these commands. The first argument to the macro is the ID number of the menu or accelerator key. The second argument to the macro is the handler function name, such as OnAbout.

Note:

Message-handler functions in this category are not predeclared in class CWnd. The ON_COMMAND mechanism provides for your own messages, which cannot be anticipated.

Handler functions for notification messages from child windows to a parent window follow the same rules as those for WM_COMMAND messages. For example, you might call the handler function for a BN_CLICKED message OnBnClicked.

Handler functions for other messages, such as WM_PAINT and WM_CREATE, have strict requirements for names and argument signatures. Class CWnd lists prototypes for these message handlers—each prototype is preceded by the identifier afx_msg. Class CWnd is declared in file AFXWIN.H.

The handler for the WM_CREATE message, for instance, must be named
OnCreate and must take one argument of type LPCREATESTRUCT, a Windows type. The function returns an int.

Note:

Keep in mind that your message-handler functions in this category are overriding the predefined versions declared in class CWnd.

The macros used in message maps for these functions prefix the message
name with ON_—for example, ON_WM_CREATE. The macros take no arguments.