MFC 对话框中动态创建N级菜单以及响应事件

时间:2021-12-16 12:13:32

创建一个基于对话框的工程,工程名为CreateMenu

为该对话框增加一个文件菜单项和测试菜单项,如下图所示

MFC 对话框中动态创建N级菜单以及响应事件 MFC 对话框中动态创建N级菜单以及响应事件

测试菜单项至少要有一个子菜单项

在对话框属性中关联该菜单

在resource.h中增加一个ID_TESTMENU宏

#define ID_TESTMENU          5000

在对话框中添加一个Button按钮,建立消息映射,编辑代码如下

void CCreateMenuDlg::OnButton1() 
{
    // TODO: Add your control notification handler code here
    char buf[2];
    //获取*菜单
    CMenu* pMenu=GetMenu();
    //获取1级菜单
    CMenu* pFileMenu=pMenu->GetSubMenu(0);
    CMenu* pTestMenu=pMenu->GetSubMenu(1);
    //添加2级菜单
    if(pTestMenu->GetSafeHmenu()==NULL) 
        return;
    //添加一个2级弹出菜单,将"文件"菜单项作为该菜单的子菜单
    pTestMenu->AppendMenu(MF_POPUP,(UINT)pFileMenu->m_hMenu,"文件");
    //添加一个2级弹出菜单,该菜单的子菜单为空
    pTestMenu->AppendMenu(MF_POPUP,(UINT)pTestMenu->m_hMenu,"测试");
    //添加10个2级普通菜单
    for(UINT m_ID=1;m_ID<=10;m_ID++)
    {
        itoa(m_ID,buf,10);
        pTestMenu->AppendMenu(MF_SEPARATOR);
        pTestMenu->AppendMenu(
            MF_STRING,m_ID+ID_TESTMENU,"2级菜单"+CString(buf));
    }
 
    //添加n级菜单
    CMenu* pnMenu=pTestMenu->GetSubMenu(2);
    pnMenu->AppendMenu(MF_POPUP,(UINT)pnMenu->m_hMenu,"3级菜单");
    for(int i=0;i<5;i++)
    {
        pnMenu=pnMenu->GetSubMenu(0);
        if(pnMenu==NULL) return;
        itoa(i+4,buf,10);
        pnMenu->AppendMenu(
            MF_POPUP,(UINT)pnMenu->m_hMenu,buf + CString("级菜单"));
    }
    pnMenu->GetSubMenu(0)->AppendMenu(
        MF_STRING,ID_TESTMENU,"9级菜单");
}

响应单击菜单的事件

添加OnCommand的消息映射,编辑代码如下

BOOL CCreateMenuDlg::OnCommand(WPARAM wParam, LPARAM lParam) 
{
    // TODO: Add your specialized code here and/or call the base class
    UINT uMsg=LOWORD(wParam);
    char buf[2];
    if(uMsg==ID_TESTMENU)
    {
                MessageBox("HELLO!");
    }
    for(UINT i=1;i<=10;i++)
    {
        if(uMsg==ID_TESTMENU+i)
        {
            itoa(i,buf,10);
            MessageBox("HELLO! " + CString(buf));
        }
    }
    return CDialog::OnCommand(wParam, lParam);
}

运行结果:

MFC 对话框中动态创建N级菜单以及响应事件

源码下载