Step 3: Adding a Property to the Control

IPolyCtl is the interface that contains your custom methods and properties. The easiest way to add a property to this interface is to right-click it in ClassView and select Add Property.

The Add Property to Interface dialog box appears, allowing you to enter the details of the property you want to add:

  1. On the drop-down list of property types, select short.

  2. Type "Sides" as the Property Name. As you edit the Property Name field, the Implementation box shows the lines that will be added to your IDL file.

  3. Click OK to finish adding the property.

MIDL (the program that compiles .idl files) defines a Get method that retrieves the property and a Put method that sets the property. When MIDL compiles the file, it automatically defines those two methods in the interface by prepending put_ and get_ to the property name.

Along with adding the necessary lines to the .idl file, the Add Property to Interface dialog box also adds the Get and Put function prototypes to the class definition in PolyCtl.h and adds an empty implementation to PolyCtl.cpp.

To set and retrieve the property you need a place to store it. From FileView, open PolyCtl.h and add the following line at the end of the class definition after m_clrFillColor is defined:

     short m_nSides; 

Now you can implement the Get and Put methods. The get_Sides and put_Sides function definitions have been added to PolyCtl.h. You need to add code in PolyCtl.cpp to match the following:

STDMETHODIMP CPolyCtl::get_Sides(short *pVal)
{
   *pVal = m_nSides;
   return S_OK;
}

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

The get_Sides function simply returns the current value of the Sides property through the pVal pointer. In the put_Sides method, you make sure the user is setting the Sides property to an acceptable value. You need more than 2 sides, and since you will be storing an array of points for each side later on, 100 is a reasonable limit for a maximum value. If an invalid value is passed you use the ATL Error function to set the details in the IErrorInfo interface. This is useful if your container needs more information about the error than the returned HRESULT.

The last thing you need to do for the property is initialize m_nSides. Make a triangle the default shape by adding a line to the constructor in PolyCtl.h:

CPolyCtl()
{
   m_nSides = 3;
}

You now have a property called Sides. It's not much use until you do something with it, so next you will change the drawing code to use it.

Back to Step 2On to Step 4