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 - Linking up our new menus (Page 6 of 9 )
To make our menu items “clickable” and to give them a purpose, we need to add some code to our app to let the C++ compiler know that we want to execute a certain function whenever a specific menu item is clicked on.
Change the CMainWin() class declaration in menu.h, like it’s shown below:
class CMainWin : public CFrameWnd
afx_msg void OnItem1();
afx_msg void OnItem2();
afx_msg void OnItem3();
class CApp : public CWinApp
As you can see, we have added three new lines. They are MFC function declarations, which will be called whenever a menu item is clicked on. Now, we need to modify the menu.cpp file. Firstly, we need to include our ids.h file:
Next, modify the BEGIN_MESSAGE_MAP() and END_MESSAGE_MAP() lines, to look like this:
We have added three ON_COMMAND() macros to the message map for our main window. They tell the C++ compiler which messages our app will respond to. The ON_COMMAND macro takes two parameters: The first is the id of the message our app will “catch” (as defined in ids.h), and the second is the name of the function to execute whenever that message is “caught” from windows).
Therefore, whenever our app receives an IDM_1 message from windows, it will execute the CMainWin::OnItem1() function, etc.