Automation and Eventing with Word

In this article, I demonstrate several topics related to Word automation in MFC :

How to run Word 97 using automation from an MFC client using the #import compiler directive.

How to use the wrapper functions generated by #import to simply add a new document and make
Word visible to the user.

How to catch and use the exceptions generated by the wrapper classes.

How to create a Sink interface in your client to catch the application and document events fired by
Word using the connection point technology.

How to connect your Sink interface to the connection points in Word.

How to retrieve the built-in document properties of a Word Document.

Almost all topics presented here can be easily extended to any application exposing an automation interface
and its type library.

The complete example is a dialog-based MFC application provided as a zip file compiled with Visual
Studio 6.0. If you run it, you will be presented a dialog box with two buttons : "Run Word" and "Cancel".
If you push "Run Word", an instance of word is started and a new document created. You can experiment
by directly quitting Word, issuing a new document command. Note that the event handlers display
message boxes on the screen and during this time, Word will not be responding (the event are fired
synchronously), so you will have to switch to the test program and answer the message box before you can
continue. When the Close Document event is received, the number of pages in the document is computed
and displayed in the message box (Just press several CTRL ENTER to insert new pages before leaving
Word and you will see the page count incrementing). When you quit Word, the event will be trapped and
the application terminated. If you push "Cancel" after Word has been started, the application will terminate
Word before killing itself.

Information concerning Word automation can be found in the following Microsoft Knowledge Base articles
:

Q181845 : Create a Sink Interface in MFC-Based COM client

Q183599 : Catch Microsoft Word97 Application Events Using VC++

Q152087 : Connpts.exe Implements Connection Poitns in MFC Apps

Q179494 : Use Automation to Retrieve Built-in Document Properties

Q183369 : Use Automation to Run a Word 97 Macro with Arguments

The examples provided by Microsoft are generally quite old, not very comprehensive (at least for me), not
really object oriented and do not use the new #import directive but rather the MFC ColeDispatchDriver
class. I hope I succeeded in making these examples clearer. However, I won't explain all the COM stuff
and the connection point technology. There are a lot of sources for this.

Now, let's stop talking, it's time for a little code (ok, ok, in a few lines, I promise) !

First you need Word97 installed on your machine and find the type library. For Word97, it's installed in
C:\Program Files\Microsoft Office\Office (look for msword8.olb). In addition, you will need mso97.dll and
vbeext1.olb (this one is located in C:\Program Files\Common Files\Microsoft Shared\VBA). If you ask
why you need the two other files in addition to the Word97 type library, look in the msword8.tlh (more on
this later) file generated by the #import directive and you will see a comment informing you that these are
cross-referenced type libraries needed by msword8.olb. Now that you have all these files, here is the code
to generate the wrapper classes.

You need the pragma to avoid warning messages generated by the office97 type library. The compiler will
generate two files (with extensions tlh and tli) for each #import. Using Visual Studio 6.0, you won't really
need to look at these wrapper thanks to the automatic statement completion. Let's just say that these
classes are smart pointers around the interfaces provided by Word.

Now that you have these wrapper classes, you can start Word as an automation server, add a new
document and make it visible to the user with the following code :

Easy, no ? You first declare two smart pointers : one for the _Application interface and another one for the
_Document interface. The #import has added Ptr at the end to indicate the smart pointer. __uuidof allows
you to retrieve the CLSID of the Word.Application object which is the "entry point" to the Word object
model (do not confuse _Application which is an interface with Application which is the coclass). You can
easily add a new document and make the Word application visible to the user by calling the Visible
property (this VB-like property mechanism is made possible thanks to the __declspec(property) specifier).

You will have noted the try/catch blocks. The wrapper functions you called transformed the COM errors
from HRESULT to exceptions of type _com_error (you can avoid this by calling raw functions also
provided by the wrapper). You can display the hresult and some "user friendly" error message contained in
the exception using the DumpComError function.

Well, finished with the first three topics. Now, let's dive into the more interesting part : the connection
points and events. Events can be fired by Word either at the application level or at the document level
(look in the tli file or use the OLE/COM object viewer and search for the ApplicationEvents and
DocumentEvents outgoing interfaces). You have 3 methods in the ApplicationEvents interface (Startup,
Quit and DocumentChange) and 3 in the DocumentEvents interface (New, Open and Close). Before you
can catch events in your MFC client, you need first to add a sink interface that will receive the events and
connect your sink interface to Word.

First, add a new class CWordEventSink deriving from CCmdTarget (setting the automation check box).
We will use this class as a sink for both the application events and the document events. Here is the include
file (without the unrelevant code for the discussion here).

Not too complicated indeed. You just see the methods that will be called by the message dispatching of the
CCmdTarget class based on the dispatch map defined in the source file. So, here is a part of the source
file (with only one of the event handler shown) :

The first three entries in the dispatch map are for the ApplicationEvents interface and the next three are for
the DocumentEvents interface. Pay attention here to a trick of class Wizard : DISP_FUNCTION uses
successively dispids beginning with 1, which matches exactly the dispids of events fired by Word (Startup
has dispid 1, New has dispid 4 for example as you can check in the tlb). If not the case, you should use
entries like :

Unfortunately, it seems that class wizard doesn't support this notation. Shocking !

You just need to have an instance of this CWordEventSink class but you won't receive events yet because
you still have to connect your sink class to Word (how could Word know that you would like to receive
these events). This is generally done with the AfxConnectionAdvise and AfxConnectionUnadvise functions
but I will present another more object oriented way to do it. The basic functionnality to connect and
disconnect a sink is encapsulated in a class called CConnectionAdvisor. Here is the include file :

The constructor takes a reference to the interface you need to connect (IID_IWordAppEventSink or
IID_IWordDocEventSink in the example). You call Advise when you need to connect your Sink to the
given interface in the Source (that is Word) and Unadvise to disconnect. The implementation of Advise is
very similar to the AfxConnectionAdvise but we keep a pointer to the IConnectionPoint interface to make
the implementation of Unadvise easier. If you forget to disconnect, the destructor will take care of it. Here
is the implementation :

Almost finished ! Of course, it's natural that the CWordEventSink has an instance of the
CConnectionAdvisor. As I designed the Sink to handle two outgoing interfaces, I have to insert two
CConnectionAdvisor objects in my CWordEventSink just like this :

When you need to advise or unadvise, you have to specify the source and the interface you need to
connect to. The Advise method looks a little like a QueryInterface implementation as it has to map the
specified interface to one of the CConnectionAdvisor in the class. Note that this could be automated with
some MFC like maps and macros.

Now, it's time to look at the code to connect your event. This code should be added after you created
your instance of Word and added a new document (see above).

There is something funny with some events however : you won't never receive the Startup event for
example because this event is fired by Word before you are given a chance to connect your sink to the
ApplicationEvents interface. It seems that the same applies for the document events as you need to have a
document interface before you can connect your sink to the DocumentEvents interface. At this time
however, the New and Open events have already been fired. So the only events I have been able to trap
are DocumentChange, Quit and Close.

Now ready for the last thing : retrieving built-in document properties in Word. This is interesting because
the wrapper classes will return you an IDispatch pointer to a VB collection and you have to find your way
in the collection to retrieve the property. As an example, I will provide the way to retrieve the count of
pages in a document. Exception handling is not reproduced here.

DWORD PageCount;
IDispatchPtr pDispatch(m_pWord->ActiveDocument->BuiltInDocumentProperties);
ASSERT(pDispatch != NULL);
// this pDispatch will be released by the smart pointer, so use FALSE
COleDispatchDriver DocProperties(pDispatch, FALSE);
_variant_t Property((long)Word::wdPropertyPages);
_variant_t Result;
// The Item method is the default member for the collection object
DocProperties.InvokeHelper(DISPID_VALUE,
DISPATCH_METHOD | DISPATCH_PROPERTYGET,
VT_VARIANT,
(void*)&Result,
(BYTE*)VTS_VARIANT,
&Property);
// pDispatch will be extracted from variant Result
COleDispatchDriver DocProperty(Result);
// The Value property is the default member for the Item object
DocProperty.GetProperty(DISPID_VALUE, VT_I4, &PageCount);
// The page count is now in PageCount

First you call the BuiltInDocumentProperties method to retrieve an IDispatch pointer to the collection of
document properties. You won't have much more help from the #import here but you can use the
COleDispatchDriver class to do the job. What you need to compute in fact is
"Item(wdPropertyPage).Value" in the collection. First build a first COleDispatchDriver with the IDispatch
pointer you received. The collections have a member called Item which is the default member of a
collection object, so you can use DISPID_VALUE in your call to InvokeHelper. You also have to give the
property you want to retrieve as parameter and you will receive a variant which contains a new IDispatch
for the variable you requested. Just build a new COleDispatchDriver with this IDispatch and call the
GetProperty function to retrieve the page count. As Value is the default member, you can use
DISPID_VALUE again. The great thing here is that COleDispatchDriver, _variant_t or IDispatchPtr are
doing a lot of automatic type conversions and will release all the things.

As virtualization becomes the norm throughout organizations of nearly all sizes, and as more organizations look to private cloud solutions, IT decision makers are increasingly in need of ways to keep storage costs and complexity under control in the face of often-runaway virtual machine (VM) sprawl. Application-aware storage is designed to help achieve these important goals. Read this white paper to learn how application-aware storage allows you to gain VM-level visibility into application performance and …