// Note: we add support for IID_IDefineOfficeEventSink to support typesafe binding
// from VBA. This IID must match the GUID that is attached to the
// dispinterface in the .ODL file.
HOWTO: Create a Sink Interface in MFC-Based COM Client
Article ID : 181845
Last Review : July 30, 2003
Revision : 1.0
This article was previously published under Q181845
On this Page
SUMMARY
MORE INFORMATION
REFERENCES
Note Microsoft Visual C++ .NET (2002) supports both the managed code model that is provided by the Microsoft .NET Framework and the unmanaged native Microsoft Windows code model. The information in this article applies only to unmanaged Visual C++ code.
SUMMARY
Microsoft Foundation Classes (MFC) has wizard support to add sink interfaces for ActiveX controls. However, this support does not extend to other COM servers. This article describes how to add a sink interface in an MFC client for source interfaces described by COM servers. Please note that this article applies to source interfaces, which are dispinterfaces, or dual interfaces with events being called through IDispatch::Invoke().
MORE INFORMATION
Here are the steps to add a sink interface to a COM client: 1. Using the Class Wizard, add a CCmdTarget derived object (for example, CMySink) with automation support. In the Class Wizard, select the Automation option rather than "Createable by type ID" option when adding this class.
NOTE: If you are using Visula Studio.NET do the following:
On the Project menu, select Add Class. In Add Class Dialog, select MFC Class.In MFC Class Wizard, on the Names page, under the base class, select CCmdTarget, and then under select support for automation, select Automation.
2. In the interface map, change the IID (the second parameter in the INTERFACE_PART macro) so that it is the IID of the source interface (usually the interface with the default and/or source attribute in the server's .idl file). The .idl file can be seen by viewing the typelib in the OLE/COM Object Viewer.
3. In the DISPATCH_MAP of CMySink class, add a DISP_FUNCTION_ID macro for each of the events defined in the source interface that you want to handle. For example: BEGIN_DISPATCH_MAP(CMySink, CCmdTarget)
DISP_FUNCTION_ID(CMySink,"Quit",2,OnObjQuit,VT_EMPTY,VTS_I4 VTS_I4)
END_DISPATCH_MAP()
The code above is an entry for handling the Quit event with a DISPID 2, which takes two long parameters and returns a void. OnObjectQuit is a CMySink member function that takes two longs and returns a void. This function must be added manually and is called when the COM server fires a Quit event.
4. Now you have hooked up the sink interface with the server so that you can start receiving events. To do this, call the AfxConnectionAdvise() function once the server object is created. For example: //Instantiate the sink class and hold a pointer to it.
m_pSink = new CMySink();
//Get a pointer to sinks IUnknown, no AddRef. CMySink implements only
//dispinterface and the IUnknown and IDispatch pointers will be same.
LPUNKNOWN pUnkSink = m_pSink->GetIDispatch(FALSE);
//Establish a connection between source and sink.
//m_pUnkSrc is IUnknown of server obtained by CoCreateInstance().
//m_dwCookie is a cookie identifying the connection, and is needed
//to terminate the connection.
AfxConnectionAdvise(m_pUnkSrc, IID_MYEVENT, pUnkSink, FALSE,
&m_dwCookie);
5. When you have finished using the server object you need to terminate the connection before releasing the server object. You do this by calling the AfxConnectionUnadvise() function. For example: //Get a pointer to sinks IUnknown, no AddRef.
LPUNKNOWN pUnkSink = m_pSink->GetIDispatch(FALSE);
//Terminate a connection between source and sink.
//m_pUnkSrc is IUnknown of server obtained by CoCreateInstance().
//m_dwCookie is a value obtained through AfxConnectionAdvise().
AfxConnectionUnadvise(m_pUnkSrc, IID_MYEVENT, pUnkSink, FALSE,
m_dwCookie);
Because CMySink was created on the heap, make sure you delete it to avoid memory leaks.
REFERENCES
The sink component of the Connpts.exe sample illustrates implementation of the sink interface.
For additional information, please see the following article in the Microsoft Knowledge Base:
152087 SAMPLE: Connpts.exe Implements Connection Points in MFC Apps
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 :
class CConnectionAdvisor
{
public:
CConnectionAdvisor(REFIID iid);
BOOL Advise(IUnknown* pSink, IUnknown* pSource);
BOOL Unadvise();
virtual ~CConnectionAdvisor();
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 :
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
{
--------------------------------------------------------------------------------
This article was contributed by Christian Staffe.
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.