VS2010动态添加菜单项

时间:2022-09-07 20:55:23

在VC6.0和VS2010里面动态添加菜单项是不一样的,查看MSDN文档可知,VS2010采用的是MFC9.0版,其中有很多新增的项具体信息请查看http://msdn.microsoft.com/en-us/library/ws8s10w4.aspx,本文就根据自己的测试详细的比较一下二者的区别:

1.在VC6.0里面动态添加一个子菜单项

在CMainFrame::OnCtreate()中添加代码,另外要在Resource.h里面添加#define ID_MENU_ADDMENUITEM    32773

CMainFrame::OnCtreate(){

//下面是添加的代码

CMenu *pMenu=AfxGetMainWnd()->GetMenu();
CMenu *pmSub=pMenu->GetSubMenu(1);
pmSub->AppendMenu(MF_STRING,ID_MENU_ADDMENUITEM,L"Add Menu &Item");

}//效果是在“Edit”菜单最下面添加了一个"Add Menu Item"子项

2.在VS2010里面添加一个子菜单项:

要对CMainFrame类的OnShowPopupMenu()进行重载,另外要在Resource.h里面添加#define IDS_EDIT_MYITEM_1    32773

BOOL CMainFrame::OnShowPopupMenu(CMFCPopupMenu* pMenuPopup)
{
    // TODO: Add your specialized code here and/or call the base class

    int iIndex = -1;
    if (!CMFCToolBar::IsCustomizeMode()&&(iIndex=pMenuPopup->GetMenuBar()->CommandToIndex(ID_EDIT_PASTE))>=0)
    {
        pMenuPopup->InsertSeparator(iIndex+1);
        pMenuPopup->InsertItem(CMFCToolBarMenuButton(IDS_EDIT_MYITEM_1,NULL,-1,_T("&MyItem 1")),iIndex+2);
    }   //使用CommandToIndex()来获得菜单项的索引,然后根据索引来确定子菜单项的添加位置
    return CFrameWndEx::OnShowPopupMenu(pMenuPopup);
}//效果是在“Edit”菜单最下面添加了一个分割线和一个"MyItem 1"子项

效果如图,因为还没有为其添加处理函数,所以呈灰色:

 VS2010动态添加菜单项

给添加的子菜单项添加消息处理函数:

在MainFrame.h里面添加消息处理函数声明:

   class CMainFrame : public CFrameWnd{

//…

protected:

  afx_msg void OnEditMyItem1 ();

}

然后在MainFrame.cpp消息映射里面添加消息映射项:

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
     //…

    ON_COMMAND(IDS_EDIT_MYITEM_1, OnEditMyItem1)
END_MESSAGE_MAP()

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

CMFCMenuBar的继承关系:

CObject

    CCmdTarget

           CWnd

                   CBasePane

                          CPane

                                 CMFCBaseToolBar

                                         CMFCToolBar

                                                   CMFCMenuBar

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++