7.4 Processing Input from a Menu

When a user chooses a command from a menu, Windows sends the corresponding window procedure a WM_COMMAND message whose wParam parameter contains the menu identifier of the item. The window procedure must carry out any tasks associated with the chosen command. For example, if the user chooses the Open command, the window procedure prompts for the filename, opens the file, and displays it in the window's client area.

The most common way to process menu input is with a switch statement in the window procedure. Usually, the switch statement directs processing according to the value of the wParam parameter in the WM_COMMAND message. Each case processes a different menu identifier, as in the following example:

case WM_COMMAND:
    switch (wParam)
        {
        case IDM_NEW:
            /* operations for creating a new file       */
            break;

        case IDM_OPEN:
            /* operations for opening a file            */
            break;

        case IDM_SAVE:
            /* operations for saving this file          */
            break;

        case IDM_SAVEAS:
            /* operations for saving this file          */
            break;

        case IDM_EXIT:
            /* operations for exiting the application   */
            break;
        }
    break;

In this example, the wParam parameter contains the menu identifier of the item associated with the command the user chose. For each command the user chooses, the application performs the appropriate operations.