Udostępnij za pośrednictwem


Step 3: Adding a Property to the Control

IPolyCtl is the interface that contains the control's custom methods and properties, and you will add a property to it.

To add a property using the Add Property Wizard

  1. Right-click IPolyCtl in Class View (expand the Polygon branch to find it).

  2. On the shortcut menu, click Add, and then click Add Property.

    The Add Property Wizard will appear.

  3. In the drop-down list of property types, select SHORT.

  4. Type Sides as the Property name.

  5. Click Finish to finish adding the property.

When you add the property to the interface, MIDL (the program that compiles .idl files) defines a Get method for retrieving its value and a Put method for setting a new value. The methods are named by prepending put_ and get_ to the property name.

The Add Property Wizard adds the necessary lines to the .idl file. It also adds the Get and Put function prototypes to the class definition in PolyCtl.h and adds an empty implementation to PolyCtl.cpp. You can check this by opening PolyCtl.cpp and looking for the functions get_Sides and put_Sides.

Although you now have skeleton functions to set and retrieve the property, it needs a place to be stored. You will create a variable to store the property and update the functions accordingly.

To create a variable to store the property, and update the put and get methods

  1. From Solution Explorer, open PolyCtl.h and add the following line after the definition of m_clrFillColor:

    short m_nSides;
    
  2. Set the default value of m_nSides. Make the default shape a triangle by adding a line to the constructor in PolyCtl.h:

    m_nSides = 3;
    
  3. Implement the Get and Put methods. The get_Sides and put_Sides function declarations have been added to PolyCtl.h. Add the following code to PolyCtl.cpp to complete both methods:

    STDMETHODIMP CPolyCtl::get_Sides(short* pVal)
    {
       *pVal = m_nSides;
    
       return S_OK;
    }
    
    STDMETHODIMP CPolyCtl::put_Sides(short newVal)
    {
       if (2 < newVal && newVal < 101)
       {
          m_nSides = newVal;
          return S_OK;
       }
       else
       {
          return Error(_T("Shape must have between 3 and 100 sides"));
       }
    }
    

The get_Sides method returns the current value of the Sides property through the pVal pointer. In the put_Sides method, the code ensures the user is setting the Sides property to an acceptable value. The minimum must be 2, and because an array of points will be used for each side, 100 is a reasonable limit for a maximum value.

You now have a property called Sides. In the next step, you will change the drawing code to use it.

Back to Step 2 | On to Step 4

See Also

Reference

ATL Tutorial: ActiveX Control in a Web Page