Document Class of an Automation Server

When you select the Automation option in AppWizard, it not only enables the application as a whole to support Automation but also specifically enables the document class (in AutoClickDoc.cpp) to expose properties and methods by using Automation.

Suggested Reading in the Microsoft Foundation Class Reference

The document class provided by AppWizard is derived from CDocument; therefore, your application’s document class is derived indirectly from CCmdTarget. To be exposed through Automation, a CCmdTarget-derived class must call its member function, EnableAutomation, from its constructor and must also include a dispatch map. Dispatch maps are like MFC message maps in that you do not edit them directly. AppWizard and ClassWizard edit them for you.

The AppWizard-provided dispatch map in the document’s header file looks like this:

//{{AFX_DISPATCH(CAutoClickDoc)
   // NOTE - the ClassWizard will add and remove member 
   //    functions here.
   //    DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_DISPATCH
DECLARE_DISPATCH_MAP()

and is implemented in the document’s .CPP file like this:

BEGIN_DISPATCH_MAP(CAutoClickDoc, CDocument)
   //{{AFX_DISPATCH_MAP(CAutoClickDoc)
   // NOTE - the ClassWizard will add and remove mapping macros here.
   //     DO NOT EDIT what you see in these blocks of generated code!
   //}}AFX_DISPATCH_MAP
END_DISPATCH_MAP()

As you will see in Steps 2 and 3 of AutoClik, whenever you add a new property or method, ClassWizard adds an entry to the dispatch map.

The constructor of an automated CCmdTarget object must call CCmdTarget::EnableAutomation, as implemented by AppWizard:

CAutoClickDoc::CAutoClickDoc()
{
   EnableAutomation();
   
   AfxOleLockApp();
}

If the Automation server application supports being initially loaded by using Automation, then the constructor and destructor of the document class should call AfxOleLockApp and AfxOleUnlockApp, respectively. AppWizard provides the constructor and destructor of the document class. The calls to AfxOleLockApp and AfxOleUnlockApp are required so that AutoClik gracefully terminates any interactions with Automation clients before exiting.

Generally, createable objects need this. That way, if a client application creates an object of that type causing the Automation server to start, the server will exit when the object goes out of scope in the client.

CAutoClickDoc::~CAutoClickDoc()
{
   AfxOleUnlockApp();
}