Adding the ReplacePen Helper Function

In this topic, you will use WizardBar to add the member function ReplacePen.

To create the ReplacePen helper function

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

  2. From the action menu, click Add Member Function.

    The Add Member Function dialog box appears.

  3. In the Function Type edit box, type the function’s return type (in this case, void).

  4. In the Function Declaration edit box, type the declaration (function name and parameters, if any) of the new function.

    In this case, type the following:

    ReplacePen ()

    You don’t need to type a semicolon. Also, for functions such as this that take no parameters, the parentheses are optional.

  5. In the Access area, select Protected.

  6. Click OK.

    ClassWizard adds the declaration to the beginning of the first Protected section of the header file it finds (creating the section if it does not exist); creates a starter definition in the implementation file; and jumps you to the declaration.

  7. Using WizardBar, select CScribbleDoc from the Class combo box and select ReplacePen from the Members combo box.

  8. Type the following code to fill in the function definition for ReplacePen:
    m_nPenWidth = m_bThickPen ? m_nThickWidth : m_nThinWidth;
    // Change the current pen to reflect the new width.
    m_penCur.DeleteObject( );
    m_penCur.CreatePen( PS_SOLID, m_nPenWidth, RGB(0,0,0) );
    

The ReplacePen member function uses the C conditional operator (?:) to determine the pen width and return its value. Then it calls the DeleteObject member function of the current pen object and creates a new solid black pen with CreatePen, setting its width and other attributes.

Now that you’ve created ReplacePen, you want to call it from the Scribble code that initializes the pen width. This happens in the InitDocument member function code.

To incorporate ReplacePen into Scribble

  1. Using WizardBar, select CScribbleDoc in the Class combo box and InitDocument in the Members combo box. Click the action button to jump to InitDocument.

  2. In the text editor, replace the current code with the single line that calls ReplacePen:
    ReplacePen();   // Initialize pen according to current width
    

    Note   This code replaces the code you originally added in Lesson 4, Creating the View:

       m_nPenWidth = 2; // Default 2 pixel pen width
       // Solid, black pen
       m_penCur.CreatePen( PS_SOLID, m_nPenWidth, RGB( 0,0,0 ) );
    

    because this code was incorporated into the ReplacePen function.

  3. Save your work.