Declare a Message-Handling Function for a Dialog Box Control

The CDialog class, from which CPenWidthsDlg is derived, defines default handlers for the OK and Cancel buttons. The Pen Widths dialog box contains a third button, the Default button. For CPenWidthsDlg to respond when the user clicks this button, you must define a new message handler and bind it to the Default button.

Binding a message handler to a control in a dialog box is similar to binding a message handler to a menu command, which was described in Bind Scribble’s Clear All Command to Its Handler in Lesson 6; both can be accomplished using the New Windows Message Handler dialog box.

Adding the Message Handler for the Default Button

The following procedure assumes you have PenWidthsDlg.cpp open in the text editor.

To add a message handler for the Default button

  1. Using WizardBar, click CPenWidthsDlg in the Class combo box.

  2. Click the action button arrow, located on the right end of WizardBar.

  3. On the action menu, click Add Windows Message Handler.

    Note   For a dialog class, the Class or object to handle box lists the IDs of all the controls in the dialog box, not the commands in a menu. Dialog classes also handle messages differently: the message being handled is a Windows control notification message, not an application-specific command. As a result, the New Windows messages to handle box displays more than just COMMAND and UPDATE_COMMAND_UI. It displays all the messages that can be sent by the object that’s highlighted in the Class or object to handle box.

  4. In the Class or object to handle box, select IDC_DEFAULT_PEN_WIDTHS. This is the ID of the Default button you created.

    The New Windows messages to handle box now shows all the notification messages that a pushbutton can send; namely, BN_CLICKED and BN_DOUBLECLICKED.

  5. In the New Windows messages to handle box, select the BN_CLICKED message.

  6. Click Add and Edit to create the function.

    The Add Member Function dialog box appears, displaying the candidate name, OnDefaultPenWidths. ClassWizard has synthesized this name from the object’s ID and the message name.

  7. Click OK to accept the function name offered by ClassWizard.

ClassWizard generates a starter function definition in PenWidthsDlg.cpp for the OnDefaultPenWidths message handler. Class Wizard also inserts the member function declaration into PenWidthsDlg.h, and an entry in the message map in PenWidthsDlg.cpp indicating that the member function OnDefaultPenWidths is the message handler called whenever the control IDC_DEFAULT_PEN_WIDTHS sends a BN_CLICKED message.

Right now the CPenWidthsDlg class doesn’t have any member variables defined; you will define those members in the next topic, Map the Controls to Member Variables. You will implement OnDefaultPenWidths later, in Implementing the Message Handler, after you’ve added the member variables.