The CMenu Class

Up to this point, the application framework and the menu editor have shielded you from the menu class, CMenu. A CMenu object can represent each Windows menu, including the top-level menu items and associated pop-up menus. Most of the time, the menu's resource is directly attached to a frame window when the window's Create or LoadFrame function is called, and a CMenu object is never explicitly constructed. The CWnd member function GetMenu returns a temporary CMenu pointer. Once you have this pointer, you can freely access and update the menu object.

Suppose you want to switch menus after the application starts. IDR_MAINFRAME always identifies the initial menu in the resource script. If you want a second menu, you use the menu editor to create a menu resource with your own ID. Then, in your program, you construct a CMenu object, use the CMenu::LoadMenu function to load the menu from the resource, and call the CWnd::SetMenu function to attach the new menu to the frame window. Then you call the Detach member function to separate the object's HMENU handle so that the menu is not destroyed when the CMenu object goes out of scope.

You can use a resource to define a menu, and then your program can modify the menu items at runtime. If necessary, however, you can build the whole menu at runtime, without benefit of a resource. In either case, you can use CMenu member functions such as ModifyMenu, InsertMenu, and DeleteMenu. Each of these functions operates on an individual menu item identified by ID or by a relative position index.

A menu object is actually composed of a nested structure of submenus. You can use the GetSubMenu member function to get a CMenu pointer to a pop-up menu contained in the main CMenu object. The CMenu::GetMenuString function returns the menu item string corresponding to either a zero-based index or a command ID. If you use the command ID option, the menu is searched, together with any submenus.