Menu programming is the next step to be learnt in MFC after learning message maps. MFC provides two ways of programming menus. One is by using the resource option and the second is by using the dynamic menu option. This
part of MFC Tutorial discusses about the Resource option.
The following steps will explain how to add a menu to this MFC Tutorial application.
Step 1:
Create the project with out adding any files by selecting “Empty project” option.
Step 2:
After the project gets created, click on Project –> Add To Project –> New and select SourceFile (.cpp File) option. Give any name to the file and click OK.
Step 3:
Copy the previous MFC Tutorial 2 code. Do not forget to choose the MFC Library by clicking Menu –> Project –> Settings –> General –> Microsoft Foundation Classes as “Use MFC as Shared Library”.
Step 4:
Choose Menu –> Insert –> Resource. Select Menu from the list of resources. Click “New” and create one popup item as “File” and one menu item under this “File” as “New”. Press enter on this “New” menu item and open the properties. Enter IDM_FILE_NEW as the menu resource ID in the resource id box. Press the Enter key again.
Step 5:
A new resource file will be created. Save this resource file.
Step 6:
Click Project –> Add To Project –> Files and select the two new files
Script1.rc and resource.h.
Step 7:
Now add the highlighted code into the project at the appropriate places. This code shows you how to load the menu resource into a CMenu class set the menu to the window writing handlers for the menu items.
//MFC_Tutorial_5.cpp #include #include "resource.h" class MFC_Tutorial_Window :public CFrameWnd { CMenu menu1; public: MFC_Tutorial_Window() { Create(NULL,"MFC Tutorial Part 1 CoderSource Window"); menu1.LoadMenu(IDR_MENU1); SetMenu(&menu1); } void OnFileNew(); DECLARE_MESSAGE_MAP() }; BEGIN_MESSAGE_MAP( MFC_Tutorial_Window, CFrameWnd) ON_COMMAND(IDM_FILE_NEW,OnFileNew) END_MESSAGE_MAP() void MFC_Tutorial_Window::OnFileNew() { MessageBox("Clicked File->New"); } class MyApp :public CWinApp { MFC_Tutorial_Window *wnd; public: BOOL InitInstance() { wnd = new MFC_Tutorial_Window(); m_pMainWnd = wnd; m_pMainWnd->ShowWindow(1); return 1; } }; MyApp theApp;
Please find the sample code for this mfc tutorial here.