windowsvisual-c++cmenu

How to append a dynamic menu item after call CMenu::LoadMenu?


In my project, there is a menu that need to be appended an item dynamically. In original code, items in the menu are stationary. So the menu is defined in the resource file:

IDM_SERVER_OPTIONS MENU DISCARDABLE
BEGIN
    POPUP ""
    BEGIN
        MENUITEM "&Connect", IDC_LAUNCHITEM_CONNECT
        MENUITEM "&Delete",  IDC_REMOVE_SERVER
    END
END

and is loaded in the code:

CMenu menu;
menu.LoadMenu(IDM_SERVER_OPTIONS);

Now, there is a new requirement that need to append a dynamic menu item after load the resource menu. I referred this aricle: Dynamic menu using mfc Followed it, I wrote these code:

CMenu menu;
menu.LoadMenu(IDM_SERVER_OPTIONS);
CMenu *autoConnectMenu = new CMenu;
autoConnectMenu->CreatePopupMenu();
autoConnectMenu->AppendMenu(MF_STRING | MF_ENABLED,
                            IDC_MENU_AUTO_CONNECT_SERVER, 
                            utils::LoadString(IDS_MENU_AUTO_CONNECT_SERVER));
menu.AppendMenu(MF_POPUP,
                (UINT)autoConnectMenu->m_hMenu,
                L"auto connect server");

Unfortunately, it doesn't work. The new menu item "auto connect server" can't be displayed. Then, I tried the HMENU function:

CMenu menu;
menu.LoadMenu(IDM_SERVER_OPTIONS);
AppendMenu((HMENU)menu.GetSubMenu(0),
           MF_STRING | MF_ENABLED,
           IDC_AUTO_CONNECT_SERVER,
           utils::LoadString(IDS_MENU_AUTO_CONNECT_SERVER));

It works fine!

I want to know what problem in my former code? Appreciate!


Solution

  • I think that I have found the issue. I should have called

    menu.GetSubMenu(0)->AppendMenu(...);
    

    instead of

    menu.AppendMenu(...);