René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

Automation of WinWord using COM and C++ without MFC

One of the nuisances when trying to figure out how word (or excel for that matter) can be automated using COM and C++ is that most of the examples on MSDN seem to use MFC, particularly CComObject.
Of course, this doesn't help understand it. Also, when I did my research on this subject, I found there are many seekers on usenet whose desire is to understand and not to copy the solutions. This page tries to explain COM Automation to those who want to do it in C++ and plain C++ alone.
I have learned the easiest path to start with COM Automation is by opening MS Word and have it record a Macro. For example, the following Macro writes some text (Drawings with COM Automation), alters this text's font and size, and draws a line:
Selection.TypeText Text:="Drawings with COM Automation"
Selection.HomeKey Unit:=wdLine
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Font.Bold = wdToggle
Selection.Font.Name = "Verdana"
Selection.Font.Size = 20
Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.TypeParagraph
Selection.TypeParagraph
Selection.TypeParagraph
Selection.TypeParagraph
ActiveDocument.Shapes.AddLine(126.75, 189#, 411.75, 350.25).Select

IDispatch

Now, if you're using COM/Automation, you basically use the interface IDispatch to accomplish this. Because IDispatch is not so easy to use, I have written a wrapper class (Dispatch) that can be used instead.
But before you can use IDispatch (or Dispatch, respectivly), you must first get hold of such a biest. This can be done via the Object Automation:
Automation automation;
Dispatch dispWord = automation.GetDispatch(L"Word.Application");
IDispatch can basically do three things: invoke methods, set properties, and get properties.

Setting a property

The class Dispatch allows you to set a property with its overloaded operator[]. The following line sets the property Visible to true:
dispWord[L"Visible"] = V(true);
Getting a property
Properties are gotten also with the operator[]. Here, a property with the name Documents is fetched. This property happens to be a Dispatch as well:
Dispatch docs=dispWord[L"Documents"];

Invoking a method

following line, Add returns a Dispatch (which is a dispatch for a document).

The office object model