Your browser doesn't support JavaScript Processing Messages – Windows Programming

Processing Messages

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:

  • CMainFrame is the class implementing the message map.
  • CFrameWnd is its base class.
  • ON_WM_LBUTTONDOWN() maps the left mouse button click message (WM_LBUTTONDOWN) to the handler OnLButtonDown().

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() → Handles WM_PAINT
  • OnCreate() → Handles WM_CREATE
  • OnClose() → Handles WM_CLOSE
  • OnSize() → Handles WM_SIZE
  • OnLButtonDown() → Handles WM_LBUTTONDOWN
  • OnKeyDown() → Handles WM_KEYDOWN
Windows MessageMessage Map MacroHandler Function
WM_PAINTON_WM_PAINT()OnPaint()
WM_CREATEON_WM_CREATE()OnCreate()
WM_CLOSEON_WM_CLOSE()OnClose()
WM_SIZEON_WM_SIZE()OnSize()
WM_LBUTTONDOWNON_WM_LBUTTONDOWN()OnLButtonDown()
WM_KEYDOWNON_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.