Reputation: 51
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 ?
Upvotes: 0
Views: 1707
Reputation: 51395
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.
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 );
MENUITEMINFO
structureMENUITEMINFO 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" );
MyMainMenu.SetMenuItemInfo( IDM_ITEM_TO_BE_REPLACED,
&miiNew,
FALSE );
DrawMenuBar( hWnd );
The call to DrawMenuBar
is required whenever a window's menu is modified.
Upvotes: 2