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.
#pragma warning (disable:4146)
#import "mso97.dll"
#pragma warning (default:4146)
#import "vbeext1.olb"
#import "msword8.olb" rename("ExitWindows", "WordExitWindows")
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 :
Word::_ApplicationPtr m_pWord;
Word::_DocumentPtr m_pDoc;
try
{
HRESULT hr = m_pWord.CreateInstance(__uuidof(Word::Application));
ASSERT(SUCCEEDED(hr));
m_pDoc = m_pWord->Documents->Add();
m_pWord->Visible = VARIANT_TRUE;
}
catch (_com_error& ComError)
{
DumpComError(ComError);
}
void DumpComError(const _com_error& e)
{
CString ComErrorMessage;
ComErrorMessage.Format("COM Error: 0x%08lX. %s",e.Error(), e.ErrorMessage());
AfxMessageBox(ComErrorMessage);
}
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).
const IID IID_IWordAppEventSink = __uuidof(Word::ApplicationEvents);
const IID IID_IWordDocEventSink = __uuidof(Word::DocumentEvents);
class CWordEventSink : public CCmdTarget
{
public:
CWordEventSink();
virtual ~CWordEventSink();
protected:
afx_msg void OnAppStartup();
afx_msg void OnAppQuit();
afx_msg void OnAppDocumentChange();
afx_msg void OnDocNew();
afx_msg void OnDocOpen();
afx_msg void OnDocClose();
};
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) :
BEGIN_DISPATCH_MAP(CWordEventSink, CCmdTarget)
DISP_FUNCTION(CWordEventSink, "Startup",OnAppStartup,VT_EMPTY, VTS_NONE)
DISP_FUNCTION(CWordEventSink, "Quit",OnAppQuit,VT_EMPTY, VTS_NONE)
DISP_FUNCTION(CWordEventSink, "DocumentChange", OnAppDocChange,VT_EMPTY, VTS_NONE)
DISP_FUNCTION(CWordEventSink, "New",OnDocNew,VT_EMPTY, VTS_NONE)
DISP_FUNCTION(CWordEventSink, "Open",OnDocOpen,VT_EMPTY, VTS_NONE)
DISP_FUNCTION(CWordEventSink, "Close",OnDocClose,VT_EMPTY, VTS_NONE)
END_DISPATCH_MAP()
BEGIN_INTERFACE_MAP(CWordEventSink, CCmdTarget)
INTERFACE_PART(CWordEventSink, IID_IWordAppEventSink, Dispatch)
INTERFACE_PART(CWordEventSink, IID_IWordDocEventSink, Dispatch)
END_INTERFACE_MAP()
void CWordEventSink::OnAppQuit()
{
AfxMessageBox("AppQuit event received");
}
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 :
DISP_FUNCTION_ID(CWordEventSink, "Quit", 0x02, OnAppQuit, VT_EMPTY, VTS_NONE)
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 :
class CConnectionAdvisor
{
public:
CConnectionAdvisor(REFIID iid);
BOOL Advise(IUnknown* pSink, IUnknown* pSource);
BOOL Unadvise();
virtual ~CConnectionAdvisor();
private:
CConnectionAdvisor();
CConnectionAdvisor(const CConnectionAdvisor& ConnectionAdvisor);
REFIID m_iid;
IConnectionPoint* m_pConnectionPoint;
DWORD m_AdviseCookie;
};
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 :
CConnectionAdvisor::CConnectionAdvisor(REFIID iid) : m_iid(iid)
{
m_pConnectionPoint = NULL;
m_AdviseCookie = 0;
}
CConnectionAdvisor::~CConnectionAdvisor()
{
Unadvise();
}
BOOL CConnectionAdvisor::Advise(IUnknown* pSink, IUnknown* pSource)
{
if (m_pConnectionPoint != NULL)
{
return FALSE;
}
BOOL Result = FALSE;
IConnectionPointContainer* pConnectionPointContainer;
if (FAILED(pSource->QueryInterface(
IID_IConnectionPointContainer,
(void**)&pConnectionPointContainer;)))
{
return FALSE;
}
if (SUCCEEDED(pConnectionPointContainer->FindConnectionPoint(m_iid, &m;_pConnectionPoint)))
{
if (SUCCEEDED(m_pConnectionPoint->Advise(pSink, &m;_AdviseCookie)))
{
Result = TRUE;
}
else
{
m_pConnectionPoint->Release();
m_pConnectionPoint = NULL;
m_AdviseCookie = 0;
}
}
pConnectionPointContainer->Release();
return Result;
}
BOOL CConnectionAdvisor::Unadvise()
{
if (m_pConnectionPoint != NULL)
{
HRESULT hr = m_pConnectionPoint->Unadvise(m_AdviseCookie);
m_pConnectionPoint->Release();
m_pConnectionPoint = NULL;
m_AdviseCookie = 0;
}
return TRUE;
}
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 :
class CWordEventSink : public CCmdTarget
{
public:
BOOL Advise(IUnknown* pSource, REFIID iid);
BOOL Unadvise(REFIID iid);
private:
CConnectionAdvisor m_AppEventsAdvisor;
CConnectionAdvisor m_DocEventsAdvisor;
};
Here are the new two functions Advise and Unadvise as well as the new CwordEventSink constructor :
CWordEventSink::CWordEventSink() :
m_AppEventsAdvisor(IID_IWordAppEventSink),
m_DocEventsAdvisor(IID_IWordDocEventSink)
{
EnableAutomation();
}
BOOL CWordEventSink::Advise(IUnknown* pSource, REFIID iid)
{
IUnknown* pUnknownSink = GetInterface(&IID;_IUnknown);
if (pUnknownSink == NULL)
{
return FALSE;
}
if (iid == IID_IWordAppEventSink)
{
return m_AppEventsAdvisor.Advise(pUnknownSink, pSource);
}
else if (iid == IID_IWordDocEventSink)
{
return m_DocEventsAdvisor.Advise(pUnknownSink, pSource);
}
else
{
return FALSE;
}
}
BOOL CWordEventSink::Unadvise(REFIID iid)
{
if (iid == IID_IWordAppEventSink)
{
return m_AppEventsAdvisor.Unadvise();
}
else if (iid == IID_IWordDocEventSink)
{
return m_DocEventsAdvisor.Unadvise();
}
else
{
return FALSE;
}
}
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).
CWordEventSink m_WordEventSink
BOOL Res = m_WordEventSink.Advise(m_pWord, IID_IWordAppEventSink);
ASSERT(Res == TRUE);
Res = m_WordEventSink.Advise(m_pDoc, IID_IWordDocEventSink);
ASSERT(Res == TRUE);
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);
COleDispatchDriver DocProperties(pDispatch, FALSE);
_variant_t Property((long)Word::wdPropertyPages);
_variant_t Result;
DocProperties.InvokeHelper(DISPID_VALUE,
DISPATCH_METHOD | DISPATCH_PROPERTYGET,
VT_VARIANT,
(void*)&Result;,
(BYTE*)VTS_VARIANT,
&Property;);
COleDispatchDriver DocProperty(Result);
DocProperty.GetProperty(DISPID_VALUE, VT_I4, &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.
Happy Automation