[MFC]菜单CMenu用法

CMFCToolBar工具栏按钮添加下拉菜单

1. 在资源视图下制作下拉菜单IDR_MENU_LIST

  • Menu1 --- ID_MENU_1
  • Menu2 --- ID_MENU_2
  • Menu3 --- ID_MENU_3

2. 在MainFrm文件OnCreate函数中添加如下代码

    CMenu Menu;
    CMenu* subMenu;
    
    Menu.LoadMenu(IDR_MENU_LIST);
    subMenu = Menu.GetSubMenu(0);

    int iImage = 7;    //对应工具栏中的第7个图标
    m_wndToolBar.ReplaceButton (ID_MENU,   //对应工具栏中第7个图标的ID
                CMFCToolBarMenuButton(ID_MENU,  (HMENU)*subMenu, iImage, NULL, FALSE));

    subMenu = NULL;

3.添加菜单项响应函数

    void CMyTestView::OnMenu1()
    {
        AfxMessageBox(_T("OnMenu1"));

    }

动态添加右键弹出菜单

   给窗口添加WM_RBUTTONDOWN消息,并添加如下代码

    //创建菜单
    CMenu menu;

    //设置菜单底色
    CBrush brush;
    brush.CreateSolidBrush(RGB(255, 255, 255));
    MENUINFO mi;  
    mi.cbSize = sizeof(MENUINFO);  
    mi.fMask = MIM_BACKGROUND;  
    mi.hbrBack = (HBRUSH)brush;  
    SetMenuInfo((HMENU)(menu.m_hMenu), &mi); 

    //添加菜单项
    menu.CreatePopupMenu();
    menu.AppendMenu(MF_STRING | MF_ENABLED, 1001, _T("Item1"));
    menu.AppendMenu(MF_STRING | MF_ENABLED, 1002, _T("Item2"));
    menu.AppendMenu(MF_STRING | MF_ENABLED, 1003, _T("Item3"));
    //menu.AppendMenu(MF_STRING | MF_ENABLED, 1004, _T("Item4"));
    menu.AppendMenu(MF_SEPARATOR, NULL);
    menu.AppendMenu(MF_STRING | MF_ENABLED, 1005, _T("Item5"));
    menu.AppendMenu(MF_STRING | MF_ENABLED, 1006, _T("Item6"));

    //添加二级菜单
    CMenu subMenu;
    subMenu.CreatePopupMenu();
    menu.InsertMenu(3, MF_BYPOSITION | MF_POPUP | MF_STRING,(UINT)subMenu.m_hMenu, _T("ParentItem"));
    subMenu.AppendMenu(MF_STRING | MF_ENABLED, 1007, _T("SubItem1"));
    subMenu.AppendMenu(MF_STRING | MF_ENABLED, 1008, _T("SubItem2"));
    subMenu.AppendMenu(MF_STRING | MF_ENABLED, 1009, _T("SubItem3"));
    subMenu.AppendMenu(MF_STRING | MF_ENABLED, 1010, _T("SubItem4"));
    subMenu.AppendMenu(MF_STRING | MF_ENABLED, 1011, _T("SubItem5"));

    //显示菜单

    CRect rcWindow;
    GetWindowRect(&rcWindow);
    CPoint ptMenu;
    ptMenu.x = rcWindow.left + point.x;
    ptMenu.y = rcWindow.top + point.y;
    menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, ptMenu.x, ptMenu.y, this);

    //销毁菜单
    menu.DestroyMenu();


你可能感兴趣的:(MFC)