Share via


ActiveX Controls: Advanced Topics

OverviewHow Do IFAQSample

This article covers advanced topics related to developing ActiveX controls. These include:

  • Using database classes in ActiveX Controls

  • Implementing a parameterized property

  • Handling errors in your ActiveX Control

  • Handling special keys in the control

  • Accessing dialog controls that are invisible at run time

Using Database Classes in ActiveX Controls

Because the ActiveX control classes are part of the class library, you can apply the same procedures and rules for using database classes in a standard MFC application to developing ActiveX controls that use the MFC database classes.

For a general overview of the MFC database classes, see Databases: Overview. The article introduces both the MFC ODBC classes and the MFC DAO classes and directs you to more details on either.

Implementing a Parameterized Property

A parameterized property (sometimes called a property array) is a method for exposing a homogeneous collection of values as a single property of the control. For example, you can use a parameterized property to expose an array or a dictionary as a property. In Visual Basic, such a property is accessed using array notation:

x = obj.ArrayProp(2, 3)    ' gets element of 2D array
obj.ArrayProp(2, 3) = 7    ' sets element of 2D array

Use the OLE Automation tab of ClassWizard to implement a parameterized property. ClassWizard implements the property by adding a pair of Get/Set functions that allow the control user to access the property using the above notation or in the standard fashion.

Similar to methods and properties, parameterized properties also have a limit to the number of parameters allowed. In the case of parameterized properties, the limit is 15 parameters (with one parameter reserved for storing the property value).

The following procedure adds a parameterized property, called Array, which can be accessed as a two-dimensional array of integers.

To add a parameterized property using ClassWizard

  1. With your control project open, click ClassWizard on the View menu.

  2. Click the Automation tab.

  3. Click Add Property.

  4. In the External name box, type Array.

  5. On the Implementation menu, click Get/Set Methods.

  6. In the Type box, select short for the property’s type.

  7. In the Get Function and Set Function boxes, type unique names for your Get and Set Functions or accept the default names.

  8. Using the Parameter List grid control, add a parameter, called row (type short).

  9. Using the Parameter List grid control, add a second parameter, called column (type short).

  10. Click OK to confirm your choices.

  11. Click OK to close ClassWizard.

Changes Made by ClassWizard

When you add a custom property, ClassWizard makes changes to the control class header (.H) and the implementation (.CPP) files.

The following lines are added to the control class .H file:

afx_msg short GetArray(short row, short column);
afx_msg void SetArray(short row, short column, short nNewValue);

This code declares two functions called GetArray and SetArray that allow the user to request a specific row and column when accessing the property.

In addition, ClassWizard adds the following lines to the control dispatch map, located in the control class implementation (.CPP) file:

DISP_PROPERTY_PARAM(CSampleCtrl, "Array", GetArray, SetArray, VT_I2,
       VTS_I2 VTS_I2)

Finally, the implementations of the GetArray and SetArray functions are added to the end of the .CPP file. In most cases, you will modify the SGet function to return the value of the property. The Set function will usually contain code that should execute, either before or after the property changes.

For this property to be useful, you could declare a two-dimensional array member variable in the control class, of type short, to store values for the parameterized property. You could then modify the Get function to return the value stored at the proper row and column, as indicated by the parameters, and modify the Set function to update the value referenced by the row and column parameters.

Handling Errors in Your ActiveX Control

If error conditions occur in the control, you may need to report the error to the control container. There are two methods for reporting errors, depending on the situation in which the error occurs. If the error occurs within a property’s Get or Set function, or within the implementation of an OLE Automation method, the control should call , which signals the control user that an error has occurred. If the error occurs at any other time, the control should call , which fires a stock Error event.

To indicate the kind of error that has occurred, the control must pass an error code to ThrowError or FireError. An error code is an OLE status code, which has a 32-bit value. When possible, choose an error code from the standard set of codes defined in the OLECTL.H header file. The following table summarizes these codes.

ActiveX Control Error Codes

Error Description
CTL_E_ILLEGALFUNCTIONCALL Illegal function call
CTL_E_OVERFLOW Overflow
CTL_E_OUTOFMEMORY Out of memory
CTL_E_DIVISIONBYZERO Division by zero
CTL_E_OUTOFSTRINGSPACE Out of string space
CTL_E_OUTOFSTACKSPACE Out of stack space
CTL_E_BADFILENAMEORNUMBER Bad file name or number
CTL_E_FILENOTFOUND File not found
CTL_E_BADFILEMODE Bad file mode
CTL_E_FILEALREADYOPEN File already open
CTL_E_DEVICEIOERROR Device I/O error
CTL_E_FILEALREADYEXISTS File already exists
CTL_E_BADRECORDLENGTH Bad record length
CTL_E_DISKFULL Disk full
CTL_E_BADRECORDNUMBER Bad record number
CTL_E_BADFILENAME Bad file name
CTL_E_TOOMANYFILES Too many files
CTL_E_DEVICEUNAVAILABLE Device unavailable
CTL_E_PERMISSIONDENIED Permission denied
CTL_E_DISKNOTREADY Disk not ready
CTL_E_PATHFILEACCESSERROR Path/file access error
CTL_E_PATHNOTFOUND Path not found
CTL_E_INVALIDPATTERNSTRING Invalid pattern string
CTL_E_INVALIDUSEOFNULL Invalid use of NULL
CTL_E_INVALIDFILEFORMAT Invalid file format
CTL_E_INVALIDPROPERTYVALUE Invalid property value
CTL_E_INVALIDPROPERTYARRAYINDEX Invalid property array index
CTL_E_SETNOTSUPPORTEDATRUNTIME Set not supported at run time
CTL_E_SETNOTSUPPORTED Set not supported (read-only property)
CTL_E_NEEDPROPERTYARRAYINDEX Need property array index
CTL_E_SETNOTPERMITTED Set not permitted
CTL_E_GETNOTSUPPORTEDATRUNTIME Get not supported at run time
CTL_E_GETNOTSUPPORTED Get not supported (write-only property)
CTL_E_PROPERTYNOTFOUND Property not found
CTL_E_INVALIDCLIPBOARDFORMAT Invalid clipboard format
CTL_E_INVALIDPICTURE Invalid picture
CTL_E_PRINTERERROR Printer error
CTL_E_CANTSAVEFILETOTEMP Can't save file to TEMP
CTL_E_SEARCHTEXTNOTFOUND Search text not found
CTL_E_REPLACEMENTSTOOLONG Replacements too long

If necessary, use the CUSTOM_CTL_SCODE macro to define a custom error code for a condition that is not covered by one of the standard codes. The parameter for this macro should be an integer between 1000 and 32767, inclusive. For example:

#define MYCTL_E_SPECIALERROR CUSTOM_CTL_SCODE(1000)

If you are creating an ActiveX control to replace an existing VBX control, define your ActiveX control error codes with the same numeric values the VBX control uses to ensure that the error codes are compatible.

Handling Special Keys in Your Control

In some cases you may want to handle certain keystroke combinations in a special way; for example, insert a new line when the ENTER key is pressed in a multiline text box control or move between a group of edit controls when a directional key ID pressed.

If the base class of your ActiveX control is COleControl, you can override to handle messages before the container receives them. When using this technique, always return TRUE if you handle the message in your override of PreTranslateMessage.

The following code example demonstrates a possible way of handling any messages related to the directional keys.

BOOL CSampleControl::PreTranslateMessage(LPMSG lpmsg)
{
    BOOL bHandleNow = FALSE;

    switch (lpmsg->message)
    {
    case WM_KEYDOWN:
        switch (lpmsg->wParam)
        {
        case VK_UP:
        case VK_DOWN:
        case VK_LEFT:
        case VK_RIGHT:
            bHandleNow = TRUE;
            break;
        }
        if (bHandleNow)
            OnKeyDown(lpmsg->wParam, LOWORD(lpmsg
                ->lParam), HIWORD(lpmsg->lParam));
        break;
    }
    return bHandleNow;
}

For more information on handling keyboard interfaces for an ActiveX control, see the ActiveX SDK documentation.

Accessing Dialog Controls That Are Invisible at Run Time

You can create dialog controls that have no user interface and are invisible at run time. If you add an invisible-at-run-time ActiveX control to a dialog box and use to access the control, the control will not work correctly. Instead, you should use one of the following techniques to obtain an object that represents the control:

  • On the Member Variables page of ClassWizard, select the control's ID, and click Add Variable. Enter a member variable name, select "Control" as the Category, and select the control's wrapper class as the Variable type.

     – or – 

  • Declare a local variable and subclass as the dialog item. Insert code that resembles the following (CMyCtrl is the wrapper class, IDC_MYCTRL1 is the control's ID):

    CMyCtrl myCtrl;
    myCtrl.SubclassDlgItem(IDC_MYCTRL1, this);
    // ... use myCtrl ...
    myCtrl.UnsubclassWindow();