Dal's Programming Course - Lesson 08

WM_COMMAND Messages

When a user activates a menu item, Windows sends a WM_COMMAND message to your application. One of the arguments of the WM_COMMAND message is the ID number of the menu item selected. Your program them must act on this message with the appropriate response.

As you probably have learned by now, programmers never deal directly with ID numbers, but instead deal with symbolic names that represent the ID number. Menu items are no different. You can invent your own symbolic names for each menu item, and the development system takes care of assigning an unique ID number to the name, and putting this information in the “resource.h” file.

In this lesson, we will continue to expand the program and make it sensitive to the menu commands.

Materials for this Lesson: Download.
Homework

Item

Time

Description

1 10 Mins Edit your IDR_MAINMENU menu and change the symbol IDs to ID_RED, ID_BLUE, ID_EXIT, and ID_WHO for the appropriate menu items. Note that when you create a resource item (in this case menu items), the development system uses the caption that you type to make up a symbol name. You can chose to use the made up name, or you can change it as we are doing now.
2 10 Mins As stated above, when a menu item is selected by the user, a WM_COMMAND message is sent to your application. Read about WM_COMMAND now.
3 5 Mins WM_COMMAND is ultimately routed to the WindowProc() of the window holding the menu that generated the WM_COMMAND message. Therefore, to cause your program to react to your menu, you will need to process the WM_COMMAND message in the WindowProc() located in mcTopLevelWindow. Note that you could have put code to work on WM_COMMAND in mcBasicWindow as well. Why do you think I recommend that you put it in mcTopLevelWindow? (Hint: who specified what menu to use?)
4 40 Mins You will need to write code to process a WM_COMMAND message. I recommend creating a protected method to do that. Use the following prototype:

LRESULT CommandProc(WPARAM wParam, LPARAM lParam);

Write the actual method. Extract the command out of wParam with LOWORD(). Use a switch statement on the command ID. The switch statement should have cases for the following commands: ID_RED, ID_BLUE, ID_EXIT, and ID_WHO. For the ID_RED and ID_BLUE commands, you can change the background color by resetting the m_BackGroundColor member of your class to a new value, and then calling Draw(). For ID_EXIT, you can call PostMessage() as is done in the base class. And for ID_WHO, you can use a message box to display your name.

5 10 Mins After you can compile CommandProc() without errors, you will need to change your WindowProc() in mcTopLevelWindow to call CommandProc() when a WM_COMMAND message is sent.
6 5 Mins Run your program. All the menu items should now do something. Hopefully, these all do the right thing.