简体   繁体   English

使用mfc的动态菜单

[英]Dynamic menu using mfc

I would like to add a menu item to my main menu and then populate it with items at run time. 我想在我的主菜单中添加一个菜单项,然后在运行时用项填充它。 How would I do this? 我该怎么做? And besides adding items how would I have a message map entry for them since I do not know the id? 除了添加项目,我怎么会有他们的消息映射条目,因为我不知道ID?

You can create a CMenu object dynamically like this: 您可以像这样动态创建CMenu对象:

CMenu *menu = new CMenu;
menu->CreatePopupMenu();
// Add items to the menu
menu->AppendMenu(MF_STRING, menuItemID, "Text");
...

Then add this sub-menu to your main menu: 然后将此子菜单添加到主菜单:

wnd->GetMenu()->AppendMenu(MF_POPUP, (UINT_PTR)menu->m_hMenu, "Menu Name");

As for the message map, assuming all your menu item IDs are within a certain range, you can use ON_COMMAND_RANGE to map the entire range to a single function. 对于消息映射,假设所有菜单项ID都在一定范围内,您可以使用ON_COMMAND_RANGE将整个范围映射到单个函数。 This function will receive the ID as a parameter, and within the function, you can perform different operations based on the ID. 此函数将接收ID作为参数,并且在函数内,您可以根据ID执行不同的操作。

define the menu's using #define

#define ID_SHOW   2002
#define ID_HIDE   2004

//create a menu object for main menu
CMenu *menu    = new CMenu();
menu->CreateMenu();

//another menu object for submenu
CMenu *subMenu = new CMenu();
subMenu->CreatePopupMenu();
subMenu->AppendMenu(MF_STRING, ID_HIDE, _T("four"));
subMenu->AppendMenu(MF_STRING, ID_SHOW, _T("three"));
//append submenu to menu
menu->AppendMenu(MF_POPUP|MF_STRING, (UINT)subMenu->m_hMenu,  _T("Advanced") );
SetMenu(menu);
  CMenu menuPopup;
  menuPopup.LoadMenu(IDR_CNTXT_PLAN);
subMenu.CreatePopupMenu();
 subMenu.AppendMenu(MF_STRING, MENU1,"Menu1");
subMenu.AppendMenu(MF_STRING, MENU2,"Menu2");
CMenu* pMenu = menuPopup.GetSubMenu(0);
  pMenu->InsertMenu(0,MF_BYPOSITION|MF_POPUP,(UINT)subMenu.m_hMenu,"Layers");
  menuPopup.GetSubMenu(0)->InsertMenu(1,MF_BYPOSITION|MF_SEPARATOR,0,"");
menuPopup.GetSubMenu(0)->TrackPopupMenu(TPM_LEFTALIGN, point.x, point.y, this);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM