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 the OnItem functions (Page 7 of 9 )
Our CMainWin class declaration now has three function declarations: OnItem1, OnItem2 and OnItem3. These functions need to be defined in menu.cpp. Add the following code just before the “CApp App;” line in menu.cpp:
afx_msg void CMainWin::OnItem1()
MessageBox("This is the first menu item", NULL, MB_OK | MB_ICONINFORMATION);
afx_msg void CMainWin::OnItem2()
MessageBox("This is the second menu item", NULL, MB_OK | MB_ICONINFORMATION);
afx_msg void CMainWin::OnItem3()
MessageBox("This is the third menu item", NULL, MB_OK | MB_ICONINFORMATION);
These are three similar functions, which display a message box when each menu item is clicked on. The MessageBox() function is a member of the CMainWin() class and takes three parameters:
lpszText: The text to display in the message box
lpszCaption: The text to display as the title of the message box
nType: The icon of the message box, as well as the combination of buttons which will be displayed on the message box. These are integer values that can be ored together and are defined in afxwin.h (and its other included header files). Our message box uses MB_OK (for an OK button) and MB_ICONINFORMATION (to display an information icon). Other values include: MB_ICONSTOP, MB_ICONEXCLAMATION, MB_ABORTRETRYCANCEL and MB_YESNO). Style id’s are mutually exclusive meaning that two MB_ICON… values can’t be ored together, for example.
Finally, compile and run your new menu app. It should work as expected, displaying a message box whenever a menu item is clicked on:
Now that we can create a menu, lets talk about accelerator keys and hot keys.