In part one of this series, Mitch described how to create a simple MFC based application skeleton. In this article, he builds on part one, and adds a menu to the applications main window. He also talks about accelerator keys.
Using MFC in C++ Part 2: Menus - Adding a resource file to our project (Page 3 of 9 )
It’s really simple to add a resource file to our project. Simply click on the file menu and choose the New… option. Click on the Files tab and choose the text file option. In the file name field, enter “menu.rc” and click on the OK button. If we wanted to use the built-in GUI editor to create menus using a point and click interface, we would choose the resource script option instead. But, because we chose the text file option, we will be able to build the resource file by hand, using plain text. This is the best way to learn how menus work and interact with our MFC app.
Now, double-click on the menu.rc file under the FileView tab of the Workspace window. We’re ready to create our menu!
Firstly, let’s describe the structure of a menu:
POPUP “[Item Text]”
MENUITEM “[Item Text]”, [Item Id]
MENUITEM" “[Item Text]”, [Item Id]
MenuName is the name that we will use throughout our code to reference our menu. It should start with an alphabetical character and contain only alphanumeric characters, such as MyMenu, Menu3, Red99Menu, etc. Next to the menu name, we have the MENU keyword, which tells the resource compiler that we are creating a new menu.
Next, between a set of braces, we have the POPUP keyword. This creates a new popup menu. Popup menus are the most common windows menu type, and the perfect example of a popup menu is the drop down menu that appears when you click on the “File” menu at the top of this browser window. The item text of the popup menu is enclosed in quotes and will be used to display the name of the popup menu on the menu bar. The “File” text shown in the menu at the top of this browser window is an example of a popup menus item text.
Next, we have two menu items. They are prefixed with the MENUITEM keyword, followed by the actual text that will be displayed for that item. Lastly, the item id is either a textual/numerical value, which will be used to represent the menu throughout our code. Typically, we would #define a value for each items ID in another file and include this file into the resource script. More on this in a minute.