ID Number: Q21568
2.00 2.03 2.10 3.00
WINDOWS
Summary:
Sometimes it may be desirable to add and delete menus within an
application dynamically, rather than defining the menu in the .RC
file.
Menus can be created, altered, and deleted using the following
functions:
1. CreateMenu() creates an empty menu (menu bar), which can then be
added to.
2. ChangeMenu() is used to append, insert, delete, and make other
changes to the menu (menu bar) and/or its pop-up menus.
3. SetMenu() sets a given window's menu to the one specified.
4. DrawMenuBar() redraws the menu for the specified window.
Therefore, use CreateMenu() to create the menu, use ChangeMenu() to
add menu items, use SetMenu() to attach this menu to the window, and
call DrawMenuBar() to display the menu.
Note: Remember that when SetMenu() is used, the new menu replaces the
menu that is already there. The following must be done or system
resources will decrease because the menu will not be freed when the
application exits:
1. Use GetMenu() to retrieve the current menu.
2. SetMenu() to the new menu.
3. Destroy the old menu.
More Information:
The following code example should be put in the sample Hello
application in the HelloWndProc procedure (add to HELLO.C):
#define HI_MENU 100
#define THERE_MENU 101
BOOL added_hi = FALSE;
BOOL added_there = FALSE;
HMENU hMenu;
case WM_CHAR:
if (!added_hi) {
hMenu = CreateMenu();
ChangeMenu( hMenu, NULL, (LPSTR)"Hi", HI_MENU, MF_APPEND );
SetMenu( hWnd, hMenu);
DrawMenuBar(hWnd);
added_hi = TRUE;
}
break;
case WM_COMMAND:
switch (wParam) {
case HI_MENU:
if (!added_there) {
hMenu = GetMenu(hWnd);
ChangeMenu( hMenu, 1, (LPSTR)"There", THERE_MENU, MF_APPEND;
DrawMenuBar(hWnd);
added_there = TRUE;
}
break;
case THERE_MENU:
MessageBox (hWnd, (LPSTR)"no more menus allowed",
(LPSTR)"Menu Test", MB_OK );
break;
default:
return(DefWindowProc(hWnd, message, wParam, lParam));
break;
}
break;
When a key is pressed, a WM_CHAR message will appear and will add a
menu item to the main menu bar. When the "Hi" menu item is clicked,
a WM_COMMAND message will appear that will then generate another menu
item called "There." Clicking the "There" menu item will cause a
message box to appear.