08 August 2009

an Automation server

Microsoft Word is an Automation server, which is a particular type of COM server application. Automation servers can be controlled either by talking directly to the COM interface defined by the application, or by using a Variant to talk (implicitly) to the IDispatch interface supported by the application.

To automation Word with a Variant variable (supported since Delphi 2), you initialise the Variant with a call to CreateOleObject (from the ComObj unit). Then, the Variant acts just like the object exposed by the utomation server. You can call methods and access properties, so long as you know what they are. When Word is installed, there is an optional VBA help file that can be installed as well, which describes all the functionality supported by the Word Automation object(s).

Automation through a Variant allows optional parameters to be omitted, where you are happy with their default values. So, if you are automating Microsoft Word, and you wish to save a document to disk you can call the SaveAs method of the document object, and ignore most of the eleven arameters that it takes, as shown below

More info: Delphi takes control

~~~~~~~~~~~~~~~~~~~~~~~~~
uses
ComObj;

procedure TForm1.Button1Click(Sender: TObject) ;
var
WordApplication, WordDocument: Variant;
begin
WordApplication := CreateOleObject('Word.Application') ;
WordDocument := WordApplication.Documents.Add;
WordApplication.Selection.TypeText('Hello world') ;
WordDocument.SaveAs(FileName := 'C:\Doc.Doc',
AddToRecentFiles := False) ;
WordApplication.Quit(False)
end;

0 comments: