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
{
public:
CMainWin();
afx_msg void OnItem1();
afx_msg void OnItem2();
afx_msg void OnItem3();
DECLARE_MESSAGE_MAP()
};
class CApp : public CWinApp
{
public:
BOOL InitInstance();
};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:
#include "ids.h"Next, modify the BEGIN_MESSAGE_MAP() and END_MESSAGE_MAP() lines, to look like this:
BEGIN_MESSAGE_MAP(CMainWin, CFrameWnd)
ON_COMMAND(IDM_1, OnItem1)
ON_COMMAND(IDM_2, OnItem2)
ON_COMMAND(IDM_3, OnItem3)
END_MESSAGE_MAP()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.
Next: Adding the OnItem functions >>
More C++ Articles
More By Mitchell Harper