0

I have a MFC CMenu with some items. I would like to convert or replace a single menu item with a sub-menu, with additional menu items. Is there an easy way to do that ?

Tim
  • 41
  • 7

1 Answers1

2

The CMenu class provides the class member CMenu::SetMenuItemInfo to modify an existing menu item by passing it a properly initialized MENUITEMINFO structure.

To replace a menu item with a pop-up menu (sub menu) you have to perform 3 steps.

1. Create a new pop-up menu

You can either create the menu dynamically by calling CMenu::CreatePopupMenu and populate it with CMenu::InsertMenuItem or load an existing pop-up menu from a resource using CMenu::LoadMenu:

CMenu MyMenu;
MyMenu.CreatePopupMenu();
MENUITEMINFO mii = { 0 };
mii.cbSize = sizeof( MENUITEMINFO );
mii.fMask = MIIM_ID | MIIM_STRING;
mii.wID = IDM_MY_MENU_ITEM1;   // #define this in your Resource.h file
mii.dwTypeData = _T( "Menu Item 1" );
MyMenu.InsertMenuItem( 0, &mii, TRUE );

2. Initialize a MENUITEMINFO structure

MENUITEMINFO miiNew = { 0 };
miiNew.cbSize = sizeof( MENUITEMINFO );
miiNew.fMask = MIIM_SUBMENU | MIIM_STRING;
miiNew.hSubMenu = MyMenu.Detach();   // Detach() to keep the pop-up menu alive
                                     // when MyMenu goes out of scope
miiNew.dwTypeData = _T( "Some text" );

3. Replace existing menu item

MyMainMenu.SetMenuItemInfo( IDM_ITEM_TO_BE_REPLACED,
                            &miiNew,
                            FALSE );
DrawMenuBar( hWnd );

The call to DrawMenuBar is required whenever a window's menu is modified.

IInspectable
  • 46,945
  • 8
  • 85
  • 181
  • what is 'MyMainMenu' ? Should we use 'LoadMenu()' and load our main menu into it? If yes, then can't we load the main menu into 'MyMenu' variable instead of 'CreatePopupMenu()'? – Hari Ram Mar 04 '16 at 10:40
  • @HariRam: `MyMainMenu` is a window's main menu. It doesn't matter, whether this is the result of a call to `LoadMenu()`, or created dynamically. You can create `MyMenu` from a resource as well, as long as the argument to `LoadMenu()` is a submenu. A common solution is to create a menu in the resource editor, with dummy entries for the main menu bar, adding submenus as needed. – IInspectable Mar 04 '16 at 12:06