Link to home
Start Free TrialLog in
Avatar of JohnWeidner
JohnWeidner

asked on

Reloading menus

I'd like to be able to programmatically restore my applications menu to the state it was in when the application first started.   However, since MFC keeps some of the original HMENU handles I can't simply DestroyMenu the current one and LoadMenu the new one.  Any suggestions on how to do this?
Avatar of Priyesh
Priyesh

John..
        Do u want to remove the default menu used by the MFC app and show u'r custom menu?? or do  u mean something else??? please make this point clear..
Avatar of JohnWeidner

ASKER

Edited text of question
The program allows the user to customize the menus to the point of even allowing "standard" menu items to be deleted.   I'd like to be able to restore the menu to it's previous "un-customized" state.   Since, the description of the un-customized menu is already in the resource file, I'd like to be able to LoadMenu the original menu.   I'd really rather not have to keep track of what menu items were deleted and InsertMenu them back in.
Why not just reload the menu from the resource file?   YOu could do a LoadMenu("...") and then get the handle to the old one and destroy it, and then put this one in its place or

Just make sure you use the SetMenu and Detach functions when you are ready to relate the new menu with the window.
The problem is that MFC keeps copies of the HMENU of the original menu.   So if you use DeleteMenu on the original menu, MFC will start ASSERTing because the handles it saved are no longer valid.
I solved this problem.   Basically, I deleted all the submenus of the main menu, and then insterted the subMenus from a new copy of the menu loaded from the resource file.   Here's the code:

void CMainFrame::OnRestoreMenu()
{
      CMenu * mainMenu = GetMenu() ;
      CMenu newMenu ;
      CMenu * subMenu ;
      CString menuText ;


      if (  newMenu.LoadMenu( IDR_MFCSCRTYPE ) ) {
            // new menu loaded successfully,

            // so delete all of the main menu's current menus.
            while ( mainMenu->DeleteMenu( 0, MF_BYPOSITION ) != 0 ) {
            }

            // now copy the new menu to the main menu
            int position=0;
            while ( subMenu = newMenu.GetSubMenu( position ) ) {
                  newMenu.GetMenuString( position, menuText, MF_BYPOSITION ) ;
                  mainMenu->AppendMenu( MF_POPUP, (UINT) subMenu->GetSafeHmenu(), LPCTSTR( menuText ) );
                  subMenu->Detach();
                  position++;
            }
      }
      newMenu.Detach();
      DrawMenuBar();
}
ASKER CERTIFIED SOLUTION
Avatar of sudhirbrat
sudhirbrat

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial