Redaguoti

Bendrinti naudojant


Adding a Property to the Control (ATL Tutorial, Part 3)

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

To add the property definitions to your project

  1. In Class View, expand the Polygon branch.

  2. Right-click IPolyCtl.

  3. On the shortcut menu, click Add, and then click Add Property. The Add Property wizard will appear.

  4. Type Sides as the Property Name.

  5. In the drop-down list of Property Type, select short.

  6. Click OK to finish adding the property.

  7. From Solution Explorer, open Polygon.idl and replace the following lines at the end of the IPolyCtl : IDispatch interface:

    short get_Sides();
    void set_Sides(short value);
    

    with

    [propget, id(1), helpstring("property Sides")] HRESULT Sides([out, retval] short *pVal);
    [propput, id(1), helpstring("property Sides")] HRESULT Sides([in] short newVal);
    
  8. From Solution Explorer, open PolyCtl.h and add the following lines after the definition of m_clrFillColor:

    short m_nSides;
    STDMETHOD(get_Sides)(short* pval);
    STDMETHOD(put_Sides)(short newval);
    

Although you now have skeleton functions to set and retrieve the property and a variable to store the property, you must implement the functions accordingly.

To update the get and put methods

  1. 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;
    
  2. Implement the Get and Put methods. The get_Sides and put_Sides function declarations have been added to PolyCtl.h. Now add the code for get_Sides and put_Sides to PolyCtl.cpp with the following:

    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 3, 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

Tutorial