Learning Hub Search Ctrl K

MFC › 2. Application Architecture

Command Routing and UI Updates

Who handles WM_COMMAND, and ON_UPDATE_COMMAND_UI.

intermediate #mfc#command-routing#on_command#on_update_command_ui#wm_command#notifications

Explanation

Windows messages like WM_PAINT go to one window. Commands (menu items, toolbar buttons, accelerators) are different: MFC routes a command ID through several objects until one handles it. This is why a menu item defined in the frame can be handled in the document or the view without the frame knowing.

Routing order for a command in an SDI frame (each object checks its own message map, then passes it on):

  1. the active view: and, inside it, the view’s own map;
  2. the view’s document;
  3. the frame window;
  4. the application object (CWinApp).

(MDI: active child frame first, then its view/document, then the MDI main frame, then the app.) The first object with a matching entry handles it, and routing stops.

Map entries:

Macro Handles
ON_COMMAND(id, fn) menu/toolbar/accelerator command id → void fn()
ON_COMMAND_RANGE(first, last, fn) a block of consecutive IDs → void fn(UINT id)
ON_UPDATE_COMMAND_UI(id, fn) called before the menu is shown and during idle time to enable/check/set text → void fn(CCmdUI*)
ON_BN_CLICKED(id, fn), ON_EN_CHANGE, ON_CBN_SELCHANGE … control notifications sent to the parent
ON_MESSAGE(msg, fn) custom or user message (WM_USER + n, WM_APP + n)

CCmdUI has Enable(), SetCheck(), SetRadio(), SetText(). A command with no handler is automatically disabled (greyed out): that’s the “auto disable” feature.

Example

A view that toggles a grid. The menu item ID_VIEW_GRID is defined in the resource editor; the view handles the command and keeps its check mark in sync:

#include <afxwin.h>
#include <afxext.h>

class CGridView : public CView {
    DECLARE_DYNCREATE(CGridView)
public:
    CGridView() : m_showGrid(true), m_clicks(0) {}

protected:
    bool m_showGrid;
    int  m_clicks;

    void OnDraw(CDC* pDC) override {
        CRect rc;
        GetClientRect(&rc);
        if (m_showGrid)
            for (int x = 0; x < rc.right; x += 20) { pDC->MoveTo(x, 0); pDC->LineTo(x, rc.bottom); }
        CString s;
        s.Format(_T("Clicks: %d"), m_clicks);
        pDC->TextOut(10, 10, s);
    }

    afx_msg void OnViewGrid()                    { m_showGrid = !m_showGrid; Invalidate(); }
    afx_msg void OnUpdateViewGrid(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_showGrid ? 1 : 0); }
    afx_msg void OnUpdateClear(CCmdUI* pCmdUI)   { pCmdUI->Enable(m_clicks > 0); }   // greyed when 0
    afx_msg void OnClear()                       { m_clicks = 0; Invalidate(); }
    afx_msg void OnLButtonDown(UINT nFlags, CPoint pt) { ++m_clicks; Invalidate(); CView::OnLButtonDown(nFlags, pt); }
    afx_msg void OnZoom(UINT nID) {              // one handler for a range of IDs
        AfxMessageBox(nID == ID_ZOOM_100 ? _T("100%") : _T("Other zoom"));
    }

    DECLARE_MESSAGE_MAP()
};

IMPLEMENT_DYNCREATE(CGridView, CView)

BEGIN_MESSAGE_MAP(CGridView, CView)
    ON_COMMAND(ID_VIEW_GRID, &CGridView::OnViewGrid)
    ON_UPDATE_COMMAND_UI(ID_VIEW_GRID, &CGridView::OnUpdateViewGrid)
    ON_COMMAND(ID_EDIT_CLEAR, &CGridView::OnClear)
    ON_UPDATE_COMMAND_UI(ID_EDIT_CLEAR, &CGridView::OnUpdateClear)
    ON_COMMAND_RANGE(ID_ZOOM_100, ID_ZOOM_200, &CGridView::OnZoom)
    ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()

Common pitfalls

  • Handler declared in the class but the map entry is missing (or the reverse): the command stays greyed out, with no compiler warning.
  • Putting a handler in the wrong class: a command for the document’s data belongs in CDocument; a command that needs the window (scrolling) belongs in the view.
  • ON_UPDATE_COMMAND_UI is called very often; keep it cheap and side-effect free.
  • Control IDs and command IDs share one namespace: don’t give two items the same ID by accident.
  • Toolbar buttons and menu items that share an ID are enabled/disabled together (a feature).
  • Handlers for control notifications (ON_BN_CLICKED) belong to the dialog or frame that owns the control, not to the control.

Win32 vs MFC

In raw Win32 you write a switch (LOWORD(wParam)) inside case WM_COMMAND, and enable/disable menu items manually with EnableMenuItem each time the state changes. MFC’s update-UI mechanism asks when needed instead. The routing itself can be extended by overriding OnCmdMsg.

Exercises

1. A menu command is handled in both the view and the frame. Which handler runs?

The view’s: the active view is first in the routing order, and routing stops at the first handler.