Thursday, 18 August 2011

How to handle event when user clicks on a main menu item

When you create SDI or MDI application project in Visual Studio, Wizard automatically adds a menu bar to the main window. This default, statically created menu has three items "File", "Edit" and "Help". "File"'s submenu has only one item - "Exit", but we can add our custom items. Submenu is basically a popup window and framework notifies main window when this popup is about to become active by sending WM_INITMENUPOPUP message. We can capture this event, identify popup and change default processing of this message by overloading CWnd::OnInitMenuPopup in our class.

Let's say we have added (in the resource editor) "Foo" item in a "File" submenu. All items in a main menu are identified by their indexes. Index of the first item, "File", is 0, "Edit" - 1, etc. These numbers identify these items' submenus (popups) as well and they are passed as the second argument of OnInitMenuPopup method. Now we want to enable/disable menu item named "Foo", depending on the value of some flag. Following code shows how to achieve this:


Links and references:
MFC Dialog: How to enhance a dialog-based application with Menu, Toolbar...?
Post a Comment