Learning Hub Search Ctrl K

MFC › 5. Menus, Toolbars and Ribbon

Menus and Accelerators

Menu resources, context menus and keyboard shortcuts.

beginner #mfc#cmenu#context-menu#accelerators#trackpopupmenu#update-command-ui#menu-resources

Explanation

Menus are resources: a menu bar is edited in the resource editor (IDR_MAINFRAME), where each item gets a command ID (ID_FILE_OPEN). The frame loads it with LoadFrame(IDR_MAINFRAME), together with the accelerator table, icon and title string that share the same ID.

Handling: a menu choice generates a command, routed as in Command Routing: ON_COMMAND(id, fn) to react and ON_UPDATE_COMMAND_UI(id, fn) to enable, check or rename items just before the menu opens.

Accelerators (keyboard shortcuts) are a resource of key → command ID pairs (Ctrl+O → ID_FILE_OPEN). When the frame is loaded with the shared ID, MFC translates the keys and sends the same command as the menu does. Put the shortcut text after a tab in the item caption (&Open\tCtrl+O) so it appears in the menu.

Popup (context) menus can come from a menu resource (CMenu::LoadMenu, GetSubMenu(0)) or be built in code (CreatePopupMenu, AppendMenu). Show with TrackPopupMenu, in the handler of WM_CONTEXTMENU; the point is in screen coordinates (it can be (-1,-1) when invoked from the keyboard).

Useful CMenu calls: AppendMenu(MF_STRING | MF_CHECKED | MF_SEPARATOR | MF_POPUP, id, text), EnableMenuItem, CheckMenuItem, ModifyMenu, DeleteMenu, GetMenuString. For dynamic items (recent files, plug-ins) allocate consecutive IDs and handle them with ON_COMMAND_RANGE.

Example

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

class CMainFrame : public CFrameWnd {
public:
    CMainFrame() : m_wordWrap(true), m_zoom(100) {
        m_recent = { _T("notes.txt"), _T("todo.txt"), _T("log.txt") };
    }
protected:
    bool m_wordWrap;
    int  m_zoom;
    std::vector<CString> m_recent;

    // ---- context menu built in code
    afx_msg void OnContextMenu(CWnd* /*pWnd*/, CPoint screenPt) {
        if (screenPt.x == -1 && screenPt.y == -1) {          // keyboard (Shift+F10 / menu key)
            CRect rc; GetClientRect(&rc); ClientToScreen(&rc);
            screenPt = rc.TopLeft() + CPoint(20, 20);
        }
        CMenu menu;
        menu.CreatePopupMenu();
        menu.AppendMenu(MF_STRING, ID_EDIT_COPY, _T("&Copy\tCtrl+C"));
        menu.AppendMenu(MF_STRING | (m_wordWrap ? MF_CHECKED : 0), ID_VIEW_WORDWRAP, _T("&Word wrap"));
        menu.AppendMenu(MF_SEPARATOR);

        CMenu recent;                                         // a submenu with dynamic items
        recent.CreatePopupMenu();
        for (size_t i = 0; i < m_recent.size(); ++i)
            recent.AppendMenu(MF_STRING, ID_RECENT_FIRST + static_cast<UINT>(i), m_recent[i]);
        menu.AppendMenu(MF_POPUP, reinterpret_cast<UINT_PTR>(recent.m_hMenu), _T("&Recent"));

        menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, screenPt.x, screenPt.y, this);
        // the CMenu destructor destroys the menu (and the submenu was detached by AppendMenu use)
        recent.Detach();                                      // owned by 'menu' now
    }

    afx_msg void OnWordWrap()                   { m_wordWrap = !m_wordWrap; }
    afx_msg void OnUpdateWordWrap(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_wordWrap); }
    afx_msg void OnUpdateCopy(CCmdUI* pCmdUI)   { pCmdUI->Enable(FALSE); }       // nothing selected
    afx_msg void OnRecent(UINT nID) {                        // all IDs in the range come here
        UINT index = nID - ID_RECENT_FIRST;
        if (index < m_recent.size()) AfxMessageBox(_T("Open ") + m_recent[index]);
    }
    afx_msg void OnUpdateZoom(CCmdUI* pCmdUI) {              // change the TEXT of an item
        CString s;
        s.Format(_T("Zoom: %d%%"), m_zoom);
        pCmdUI->SetText(s);
    }
    DECLARE_MESSAGE_MAP()
};

#ifndef ID_RECENT_LAST
#define ID_RECENT_LAST (ID_RECENT_FIRST + 9)
#endif

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
    ON_WM_CONTEXTMENU()
    ON_COMMAND(ID_VIEW_WORDWRAP, &CMainFrame::OnWordWrap)
    ON_UPDATE_COMMAND_UI(ID_VIEW_WORDWRAP, &CMainFrame::OnUpdateWordWrap)
    ON_UPDATE_COMMAND_UI(ID_EDIT_COPY, &CMainFrame::OnUpdateCopy)
    ON_UPDATE_COMMAND_UI(ID_VIEW_ZOOM_LABEL, &CMainFrame::OnUpdateZoom)
    ON_COMMAND_RANGE(ID_RECENT_FIRST, ID_RECENT_LAST, &CMainFrame::OnRecent)
END_MESSAGE_MAP()

Common pitfalls

  • WM_CONTEXTMENU gives screen coordinates; passing client coordinates to TrackPopupMenu shows the menu in the wrong place.
  • A CMenu object destroys its HMENU in the destructor. Don’t destroy a menu that is part of a window (GetMenu()), and Detach() a handle you hand to someone else.
  • Menu IDs for dynamic items must not collide with other IDs and must be contiguous for ON_COMMAND_RANGE.
  • Without TPM_RETURNCMD the command is posted to the window; with it, TrackPopupMenu returns the ID instead.
  • Accelerator conflicts: a key used by an edit control may be swallowed by the frame’s accelerator. Override PreTranslateMessage if needed.
  • After changing the menu bar dynamically call DrawMenuBar().
  • The menu caption text and the accelerator table are separate: changing one doesn’t change the other.

Win32 vs MFC

Win32 uses CreatePopupMenu, AppendMenu, TrackPopupMenu (same functions as MFC’s wrappers) and processes WM_COMMAND / WM_INITMENUPOPUP by hand; accelerators need TranslateAccelerator in the message loop. MFC’s UPDATE_COMMAND_UI replaces the manual WM_INITMENUPOPUP enabling logic.

Exercises

1. How do you display a context menu at the mouse position from OnContextMenu?

Use the screen point passed to the handler: menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, pt.x, pt.y, this);.