Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Creating Menus Programmatically in an MFC application

1,056 views
Skip to first unread message

Chase Vogelsberg

unread,
Jan 12, 2001, 3:47:40 PM1/12/01
to
I've a set of projects that require menus to be created and modified program-
matically rather than from the usual resource files as several of the
programs communicate with a graphics server for their display and thus
specify their menus to this third program.

So, I've been experimenting, using GetMenu to retrieve the main menu and
InsertMenu to add items. Problem is that while I can apparently add menu
items to existing sub menus, such as the File menu, the code crashes when I
add to the newly created sub menu.

// Add an "Overlay" menu :
CMenu *mnu;
mnu = AfxGetApp()->m_pMainWnd->GetMenu();
mnu->InsertMenu(2, MF_BYPOSITION | MF_ENABLED | MF_POPUP, 939, "&Overlays");

CMenu *omnu = mnu->GetSubMenu(2);
omnu->InsertMenu(0, MF_BYPOSITION | MF_ENABLED | MF_STRING, 949, "TypeOne");
omnu->InsertMenu(1, MF_BYPOSITION | MF_ENABLED | MF_STRING, 949, "TypeTwo");

According to my references, calling InsertMenu on a top level menu inserts a
new popup menu, meaning that this code should produce a new sub menu on the
main menu frame, with two sub items. Instead it crashes, as the call to
GetSubMenu() has returned a null pointer.

This despite the fact that the initial call to InsertMenu does seem to have
added a new, albeit empty, sub menu, to the window's menu frame, if I run the
code minus the last three lines shown above. (Actually, for some reason, the
Overlays menu doesn't show up until I cause the window to refresh, even when
I add a call to Invalidate(). And the new menu items, if added to the File
menu, are initially disabled despite the MF_ENABLED flag having been
specified.)

Anyone have any ideas of what I'm doing wrong, or pointers on how I can do
this dynamic creation of submenus?

TIA,

Chase Vogelsberg

David Lowndes

unread,
Jan 12, 2001, 5:01:00 PM1/12/01
to
>So, I've been experimenting, using GetMenu to retrieve the main menu and
>InsertMenu to add items. Problem is that while I can apparently add menu
>items to existing sub menus, such as the File menu, the code crashes when I
>add to the newly created sub menu.
>
> // Add an "Overlay" menu :
> CMenu *mnu;
> mnu = AfxGetApp()->m_pMainWnd->GetMenu();
> mnu->InsertMenu(2, MF_BYPOSITION | MF_ENABLED | MF_POPUP, 939, "&Overlays");

Chase,

You need to create the sub-menu popup menu first, then insert it (menu
handle) into the main menu.

The help says:

"nIDNewItem

Specifies either the command ID of the new menu item or, if nFlags is
set to MF_POPUP, the menu handle (HMENU) of the pop-up menu.
"

Dave
--
MVP VC++ FAQ: http://www.mvps.org/vcfaq
My address is altered to discourage junk mail.
Please post responses to the newsgroup thread,
there's no need for follow-up email copies.

0 new messages