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.
In Class View, expand the
Polygon
branch.Right-click
IPolyCtl
.On the shortcut menu, click Add, and then click Add Property. The Add Property wizard will appear.
Type
Sides
as the Property Name.In the drop-down list of Property Type, select
short
.Click OK to finish adding the property.
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);
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.
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;
Implement the
Get
andPut
methods. Theget_Sides
andput_Sides
function declarations have been added to PolyCtl.h. Now add the code forget_Sides
andput_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.