Since Windows is a message-oriented operating system an application will need to deal with a continual stream of notifications. Each time an event such as a keystroke or mouse click occurs, a message is sent to the application, which must then handle the event. To respond to Windows messages, a MFC application must have a message map. Message maps contain one or more macros that specify which messages will be handled by which function when an application event occurs. MFC then calls and executes the code in the function associated with the message map

The first step in adding message mapping is to declare a message map in the class’s header file using the following macro declaration DECLARE_MESSAGE_MAP(). After declaring the message map in the class header file, the message map can be defined in the class’s implementation file. This message map will start with the macro BEGIN_MESSAGE_MAP and ends with the macro END_MESSAGE_MAP. The message map macro takes two arguments: the class name, which implements the message map, and the base class for it. Between the begin and end message map will be listed the macros which represent the various categories of messages the operating system will receive. MFC provides macros for over 100 different Windows messages.

As a general rule, the name of a message map prototype will consist of the name of the message preceded by the word ‘on’ and end with a pair of parenthesis which may contain an event handler for this message. For further information on messages that have a system-defined message handler such as ‘OnPaint()’, consult with the MFC documentation. All message handlers are prototyped with the afx_msg type specifier.

In the example below a simple “hello world” application is created by adding a message map to the previous simple MFC program with a handler for the OnPaint message

#include <afxwin.h>
class CSimpleApp : public CWinApp
{
public:
BOOL InitInstance();
};
class CMainFrame : public CFrameWnd
{
public:
CMainFrame();
DECLARE_MESSAGE_MAP()
afx_msg void OnPaint();
};
BOOL CSimpleApp::InitInstance(){
m_pMainWnd = new CMainFrame();
m_pMainWnd->ShowWindow(m_nCmdShow);
return TRUE;
}
CMainFrame::CMainFrame()
{
Create(NULL, TEXT("MFC processing messages"));
}
BEGIN_MESSAGE_MAP(CMainFrame,CFrameWnd)
ON_WM_PAINT()
END_MESSAGE_MAP()
CSimpleApp MFCApp1;
afx_msg void CMainFrame::OnPaint()
{
CPaintDC dc(this);
dc.TextOut(0,0,TEXT("hello world"));
}


Download