Message Loop Alternatives

While a message loop is integral to all Windows applications, the message loop demonstrated in the WinHello application is only one format. MFC supports a second format employing message-mapping macros. In virtually all cases, the ClassWizard is used to create message-map entries which, in effect, link message commands to the message-handling functions.

Under conventional C/C++ programming, a similar process was possible using CALLBACK functions. However, MFC’s message mapping offers advantages for many functions by customizing the parameter passed to the function handling the response. For example, when the OnDraw function is called in response to a WM_PAINT message, the OnDraw function is passed a pointer to the device context as an argument, making it unnecessary to call the BeginPaint()/EndPaint() functions. Similarly, when the OnHScroll() function is called in response to a scrollbar event, parameters are passed specifying the type of event and the thumbpad position. In conventional coding, this information would still be available but would require decoding before use.

Message-mapped functions appear in many of the demos discussed in this book, but, for a very brief example, a message map containing a <SPAN class=op>ON_COMMAND</SPAN> macro might look something like this:

BEGIN_MESSAGE_MAP( CMyDoc, CDocument )
    //{{AFX_MSG_MAP( CMyDoc )
    ON_COMMAND( ID_MYCMD, OnMyCommand )
    ON_COMMAND( ID_FILE_OPEN, OnFileOpen )
    ON_WM_LBUTTONDOWN()
    ON_WM_MOUSEMOVE()
    ON_WM_LBUTTONUP()
    ON_WM_RBUTTONDOWN()
    ON_WM_RBUTTONUP()
    ON_WM_SIZE()
    // ... More entries to handle additional commands
    //}}AFX_MSG_MAP
END_MESSAGE_MAP( )

In this example, the ID_MYCMD event message is directed to the OnMyCommand() procedure, which will provide the response action. Other ON_COMMAND macro entries would be used to handle command messages generated by menus, buttons, and accelerator keys.

Likewise, the ID_FILE_OPEN event message is sent to the OnFileOpen procedure. The ON_WM_LBUTTONDOWN event and the following examples are other Windows event messages mapped to specific procedures that have been named and created—as skeletons—by the ClassWizard.

In each of these cases, the programmer must still provide the response to the message within the identified procedure. But the message maps generated by the ClassWizard are a convenient replacement for the conventional message-handling loops, which can often be quite cumbersome.

WARNING

Always use the ClassWizard to add, edit, or remove message-map entries. Manually editing the message map can quite easily cause your application to fail unceremoniously, offering little or no clue to the cause of the malfunction. Although you can edit the message map manually, you must do so in the full knowledge of what you are doing and why. And, of course, you must also check the results very carefully.

© 1998 SYBEX Inc. All rights reserved.