How to add submenu to a CMenu in MFC?

CodeFusionMobile picture CodeFusionMobile · Jul 20, 2009 · Viewed 10.5k times · Source

I have an MFC app that uses CMenu for the main menu bar.
I haven't been able to create submenus successfully.

I can have the first level of File, Edit, View, etc and their sub menus, but I can't create a submenu off of one of those menus.

For example, I would like to be able to go File->Recent Items->list of items in submenu
I can do this easily enough with the resource editor in VS, but this needs to be done dynamically.

Am I using the right class in CMenu? Any suggestions on what to try?
I haven't found any decent tutorials. Even pointing me towards the right one would be helpful.

Answer

Jared picture Jared · Jul 21, 2009

Use your resource editor to add a submenu containing one placeholder item. You can then programatically grab a reference to this submenu, add items to it and delete the placeholder item:

CMenu *subMenu = mainMenu.GetSubMenu( menuPosition );

if( subMenu )
{
    for( unsigned i = 0; i < stringArray.size(); i++ )
    {
        subMenu->AppendMenu( MF_STRING, 400 + i, stringArray[i]);
    }

    subMenu->DeleteMenu( ID_SUBMENU_PLACEHOLDER, MF_BYCOMMAND );
}