TWordApp

Methods

Constructor.Create(UseExisting : Boolean = True; Sink : Boolean = True);

If UseExisting = True then the object will try to use an already open Word application.
If Sink = True then Word events will be 'sunk' and can be 'caught' from delphi

A Global class will be registered by Word itself if there is already an instance of Word open (not necessarily opened by your program). If it is present, you can get the application object from this. If not, an exception is raised and a fresh instance of the application object needs to be created followed by the creation of a global object. You can look to see whether a running instance was used by checking the property UsedExisting, e.g., when your program closes, you may decide to close Word only if UsedExisting was false.

What if you need to activate a specific instance of Word? The Global object exposes a Tasks collection. You could iterate through these tasks and look for the instance you required.

Constructor.CreateFromOleObject(OleObject : OleVariant; Sink : Boolean = True);;

Creates TWordApp from TOleContainer.OleObject (see demo2 for more info)
If Sink = True then Word events will be 'sunk' and can be 'caught' from delphi (but see demo2 for more info)

Destructor.Destroy;

This frees the TWordApp object and in turn will free all TWordDocs and all TWordRanges. Unlike the Inprise demo, it does not close Word—I need to keep it open to allow the user to type free text and choose where to save the document.

Destructor.CloseApp(oeSaveChanges: TOleEnum);

This destructor closes all documents (saving them if indicated) and then closes Word. It then Destroys TWordApp.

DisableSystemCloseBox;

This disables the wee [x] box for the Word application and hides the system "Close" menu (not the File.Close menu though).

Activate;

This causes Word to appear and brings it to the front (see also property Visible).

AddNewDoc(Template : String) : TWordDoc;
AddOpenDoc(DocName : String) : TWordDoc;
AddActiveDoc : TWordDoc;

These methods allow you to add documents from a variety of sources. They just call the Creator methods of TWordDoc.

CloseActiveDoc(oeSaveChanges: TOleEnum);

This closes the active document and saves changes (if argument is True)

Cut;
Copy;
Paste;
Move(oeUnit : TOleEnum = wdCharacter; Count : Integer = 1);
MoveEnd(oeUnit : TOleEnum = wdCharacter; Count : Integer = 1);
MoveStart(oeUnit : TOleEnum = wdCharacter; Count : Integer = 1);
MoveRight(oeUnit : TOleEnum = wdCharacter; Count : Integer = 1; Extend : TOleEnum = wdMove);
MoveLeft(oeUnit : TOleEnum = wdCharacter; Count : Integer = 1; Extend : TOleEnum = wdMove);
MoveUp(oeUnit : TOleEnum = wdLine; Count : Integer = 1; Extend : TOleEnum = wdMove);
MoveDown(oeUnit : TOleEnum = wdLine; Count : Integer = 1; Extend : TOleEnum = wdMove);
GotoBookmark(Bookmark : String);
GoTo_(oeWhat, oeWhich : TOleEnum; oeCount: Integer = 1; oeName: String = '');
GoToNext(oeWhat : TOleEnum);
GoToPrevious(oeWhat : TOleEnum);
InsertText(Text : String);

These methods affect the active document's selection object. For information on them see the equivalent descriptions in Word's help file. Note that any action on the selection object will update the Word screen (unless ScreeUpdating is false), which is slow. It has the advantage that you can see what is going on. Generally using the range object is faster (and you can have as many as you like).

ScreenRefresh;

This does a quick update of Word's page if ScreenUpdating is false (see later).

SaveActiveDocAs(Filename : String);
UpdateActiveDocFields;

Fairly obvious methods

RunMacro(MacroName : string);

Runs the active template macro (might not see Normal.dot macros - need to check). Note macros run faster than lots of lines of Delphi COM (yes even though Word Visual Basic is interpreted). This is because it is run in the same process space. Therefor you might find it faster to call a Word macro than do lots of coding yourself. Another advantage is that it is easier to debug and you can get Word to write the macro for you using the macro recorded (although some careful pruning after to remove all the superfluous defaults may speed things up). While you cannot directly pass parameters to a macro there is no reason why you cannot add document variables or custom document properties before calling the macro and get the macro to read these and act on them. See Word help on variables and custom properties. The latest version of the Demo shows the use of custom properties to pass a parameter to a Word macro.

PrintActiveDoc;

A rudimetary print method. Note there are lots of default parameters taken for granted. Word must be visible to print (this is a limitation of Word - try printing a Word document from Explorer (right mouse click menu) and you will see Word pop up briefly. Another problem with printing is that you must let Word spool the print job before you ask it to do another print (if you try this manually in Word it will show a dialog box asking if you want to cancel the current print job). A solution to this is to use the following properties:

Application.Options.PrintBackground
Application.BackgroundPrintingStatus

You could set Word to background printing and then print a document. Continue to poll the BackgroundPrintingStatus property till it is false before printing the next document (you should have a time limit on this polling in case a printer error means Word never finishes).

ZoomFullPage;
ZoomFullWidth;

Set the zoom factor for the active document window (see also the property ZoomPerCent).  

Properties

property UsedExisting : Boolean read FUsedExisting;

You can look to see whether a running instance was used when WordApp was created by checking this property (see constructor).

property Caption : String read GetCaption write SetCaption;

This is the caption displayed in Word's title bar.

ScreenUpdating : Boolean;

Set ScreenUpdating to false prior to iterating through your bookmarks and then set it to true to reactive Word (or use ScreenRefresh). Note, while you are debugging your code, you shouldn't use ScreenUpdating = False as it will make it difficult to see what went wrong.

Visible : Boolean;

Visible can be set to make Word (yup - you guessed it) visible. When you first create a Word object it is hidden and only gets shown if you ask it to be. Note that while you can do a fair amount with Word invisible (eg open, modify and save a document), you cannot print without making Word visible first (don't ask me why).

WindowState : TOleEnum;

WindowState indicates whether Word is minimised, maximised or normal (see Word help for constant values).

Document [Index: Integer] : TWordDoc;
NoOfDocuments : Integer;

These properties allow you to retrieve documents, particularly for iterative purposes.

ZoomPerCent;

Set the zoom % for the active document window (see methods ZoomToFit and ZoomFullWidth)  

Application : _Application;
Global : _Global;

These return a COM _Application object and a COM _Global object. Useful for getting at stuff not exposed in TWordApp. The Global object is worth a look at in Word_TLB.pas as it has some useful properties and methods.The Application.System_ object is also useful as it gives you various user/machine statistics.

Events

These events are variations on the events generated by Word. The original TWord97 from Borland's demo already had sinks for the few events that word generates (see 'Event Sequences in Microsoft Word'). Word is a little inconsistent about when it generates an event (see http://www.castle.net/~bly/Programming/Delphi/index.html) so they cannot be fully relied on. You can decide whether to use the events or not in the creator for TWordApp. If you use them, TWordApp will import any existing documents into its list and will generate suitably helpful events. These events will pass the TWordApp and TWordDoc objects for your info (i.e., they are more helpful than the non-parameterised events Word generates). Note the event sink is only implemented in the Delphi 4/5 version.

Type
  TWordDocEvent = procedure (WordApp: TWordApp; WordDoc : TWordDoc) of object;

OnQuit : TNotifyEvent read GetOnQuit write SetOnQuit;

OnQuit events will only be generated by Word if there is a document present when Word closes. If Word is empty, you get no warning that it has vanished. Trying to talk to a vanished Word COM object will generate an exception (which you can trap). Prior to the OnQuit event, TWordApp will generate suitable OnCloseDocument events.

OnChangeDocument : TWordDocEvent read GetOnChangeDocument write SetOnChangeDocument;

This usually occurs when the active document changes but also seems to occur if you close a non-active document. It is generated along with OnOpenDocument and OnCloseDocument events for obvious reasons. It does not occur when the application quits. You could use this event so that you can be sure of (or force) the active document.

OnOpenDocument : TWordDocEvent read GetOnOpenDocument write SetOnOpenDocument;

This occurs when a new or existing document is opened in Word (despite Word having separate new and open events, the new event doesn't seem to work and the Open event is unreliable). TWordApp generates this event when it gets a document change event. It looks to see what has changed compared with its own internal list and fires any necessary open events for each new document. Prior to generating the event it creates suitable TWordDoc objects and adds them to its list.

OnPreCloseDocument : TNotifyEvent read GetOnPreCloseDocument write SetOnPreCloseDocument;

This is actually generated by TWordApp when it gets a close document event from Word. However Word sends this event before the document disappears (so you can still read COM object properties).  Also, if the document is closing and Word asks the user if he wants to save the document, the user has the option to say no. Thus you may find that after this event, the document is still present. If there are documents still present when Word quits it will generate just one of these events before the OnQuit event (no matter how many documents were closed when Word quit). Also, there is NO way to know which document is closing (it is usually the active one but there is no guarrantee). Therefor this event does not pass a TWordDoc object.

OnCloseDocument : TWordDocEvent read GetOnCloseDocument write SetOnCloseDocument;

This occurs when a document is closed. TWordApp generates this event when it gets a document change event. It looks to see what has changed compared with its own internal list and fires any necessary close events for each document that no longer exists in Word. After generating the event, it removes the TWordDoc object from the list and frees it.