Learning Hub Search Ctrl K

MFC › 2. Application Architecture

Message Maps

How MFC routes Windows messages and menu/button commands to your C++ member functions.

intermediate #mfc#messages#message-map#afx_msg

Explanation

Windows delivers messages (WM_PAINT, WM_LBUTTONDOWN, WM_COMMAND, …). MFC replaces the giant switch in a raw window procedure with a message map: a table that connects a message or command ID to a member function.

Three pieces are needed:

  1. DECLARE_MESSAGE_MAP() in the class declaration.
  2. BEGIN_MESSAGE_MAP(Class, BaseClass) … END_MESSAGE_MAP() in the .cpp.
  3. Handler functions declared with the afx_msg marker.

Example

#include <afxwin.h>

// ---- MainFrm.h
class CMainFrame : public CFrameWnd {
protected:
    afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
    afx_msg void OnFileHello();
    DECLARE_MESSAGE_MAP()
};

// ---- MainFrm.cpp
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
    ON_WM_LBUTTONDOWN()                                  // WM_LBUTTONDOWN -> OnLButtonDown
    ON_COMMAND(ID_FILE_HELLO, &CMainFrame::OnFileHello)  // menu item / toolbar button
END_MESSAGE_MAP()

void CMainFrame::OnLButtonDown(UINT nFlags, CPoint point) {
    CString s;
    s.Format(_T("Clicked at %d, %d"), point.x, point.y);
    AfxMessageBox(s);
    CFrameWnd::OnLButtonDown(nFlags, point);  // let the base class run too
}

void CMainFrame::OnFileHello() {
    AfxMessageBox(_T("Hello from the File menu"));
}

Pitfalls

  • A handler that is declared but missing from the map is never called, and no compiler error warns you.
  • The signature must match exactly what the ON_WM_... macro expects.
  • Message maps are not virtual functions: handlers are looked up in the map chain, base class last.
  • Always consider calling the base-class handler.

Exercises

1. Which macro maps a menu command with ID ID_APP_ABOUT to OnAppAbout?

ON_COMMAND(ID_APP_ABOUT, OnAppAbout)