MFC ActiveX Controls: Creating an Automation Server

You can develop an MFC ActiveX control as an Automation server for the purpose of programmatically embedding that control in another application and calling methods in the control from the application. Such a control would still be available to be hosted in an ActiveX control container.

To create a control as an Automation server

  1. Create the control.

  2. Add methods.

  3. Override IsInvokeAllowed.

  4. Build the control.

To programmatically access the methods in an Automation server

  1. Create an application, for example, an MFC exe.

  2. At the beginning of the InitInstance function, add the following line:

    AfxOleInit();
    
  3. In Class View, right-click the project node and select Add class from typelib to import the type library.

    This will add files with the file name extensions .h and .cpp to the project.

  4. In the header file of the class where you will call one or more methods in the ActiveX control, add the following line: #include filename.h, where file name is the name of the header file that was created when you imported the type library.

  5. In the function where a call will be made to a method in the ActiveX control, add code that creates an object of the control's wrapper class and create the ActiveX object. For example, the following MFC code instantiates a CCirc control, gets the Caption property, and displays the result when the OK button is clicked in a dialog box:

    void CCircDlg::OnOK()
    {
       UpdateData();   // Get the current data from the dialog box.
       CCirc2 circ;    // Create a wrapper class for the ActiveX object.
       COleException e;   // In case of errors
    
       // Create the ActiveX object. 
       // The name is the control's progid; look it up using OleView
       if (circ.CreateDispatch(_T("CIRC.CircCtrl.1"), &e))
       {
          // get the Caption property of your ActiveX object
          // get the result into m_strCaption
          m_strCaption = circ.GetCaption();
          UpdateData(FALSE);   // Display the string in the dialog box.
       }
       else { // An error
          TCHAR buf[255];
          e.GetErrorMessage(buf, sizeof(buf) / sizeof(TCHAR));
          AfxMessageBox(buf);   // Display the error message.
       }
    }
    

If you add methods to the ActiveX control after you use it in an application, you can begin using the latest version of the control in the application by deleting the files that were created when you imported the type library. Then import the type library again.

See also

MFC ActiveX Controls