Windows is a message-driven operating system. Every time an event occurs—such as a key press, mouse click, window resize, or paint request—the operating system sends a message to the application. The application must process these messages and respond appropriately.
In MFC, message handling is performed using a message map. A message map tells MFC which member function should be called when a particular Windows message is received.
Declaring a Message Map
The first step is to declare a message map inside the class definition (usually in the header file) using the macro:
DECLARE_MESSAGE_MAP()
This macro informs MFC that the class contains message-handling functions.
Example:
class CMainFrame : public CFrameWnd
{
public:
CMainFrame();
protected:
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
DECLARE_MESSAGE_MAP()
};
Defining the Message Map
The message map is defined in the implementation (.cpp) file.
It begins with:
BEGIN_MESSAGE_MAP(ClassName, BaseClass)
and ends with:
END_MESSAGE_MAP()
Between these two macros are entries that associate Windows messages with handler functions.
Example:
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
Here:
CMainFrameis the class implementing the message map.CFrameWndis its base class.ON_WM_LBUTTONDOWN()maps the left mouse button click message (WM_LBUTTONDOWN) to the handlerOnLButtonDown().
Message Handler Functions
Each mapped message has a corresponding member function called a message handler.
Message handlers are declared with the afx_msg specifier.
Example:
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
Implementation:
void CMainFrame::OnLButtonDown(UINT nFlags, CPoint point)
{
MessageBox(TEXT("Left mouse button clicked!"));
}
When the user clicks the left mouse button, MFC automatically calls OnLButtonDown().
Naming Convention
Message handler names generally follow this pattern:
On + MessageName
Examples include:
OnPaint()→ HandlesWM_PAINTOnCreate()→ HandlesWM_CREATEOnClose()→ HandlesWM_CLOSEOnSize()→ HandlesWM_SIZEOnLButtonDown()→ HandlesWM_LBUTTONDOWNOnKeyDown()→ HandlesWM_KEYDOWN
| Windows Message | Message Map Macro | Handler Function |
|---|---|---|
WM_PAINT | ON_WM_PAINT() | OnPaint() |
WM_CREATE | ON_WM_CREATE() | OnCreate() |
WM_CLOSE | ON_WM_CLOSE() | OnClose() |
WM_SIZE | ON_WM_SIZE() | OnSize() |
WM_LBUTTONDOWN | ON_WM_LBUTTONDOWN() | OnLButtonDown() |
WM_KEYDOWN | ON_WM_KEYDOWN() | OnKeyDown() |
MFC provides macros for over 100 different Windows messages, making it easier to handle common events without manually writing a Windows message loop.