Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TWordApplication and Word collision

Tags:

delphi

I am using TWordApplication in Delphi. My app opens new instance of word and make something on its document. Problem is when i first run my app and next open real word exe. Word exe didnt open new word instance but it link to my app instance. So when my app write to its document all text appears on exe word visible to user.

WordApp := TWordApplication.Create(nil);
WordApp.ConnectKind := ckNewInstance;
(WordApp.Documents.Add(EmptyParam,EmptyParam,EmptyParam, varFalse ));

Then the user opens Word manually.

WordApp.Selection.Text := 'test test test';

And user see 'test test test' in manually opened Word.

If i first opens Word manually and starts my app all is ok.

like image 675
userbb Avatar asked Dec 01 '25 14:12

userbb


1 Answers

This is default behaviour of Word, it uses a running instance. What you have to do is store a reference to the document you want to modify. So don't use ActiveDocument, but use the Document you stored. Because there is no guarantee that ActiveDocument is the document you think it is.

//starting Word
var
  App: TWordApplication;
  Doc: WordDocument;
begin
  App := TWordApplication.Create(nil);
  Doc := App.Documents.AddOld(EmptyVar, EmptyVar); //open new document

<..somewhere else..>
  //modifying Word
  Doc.DoWhateverIWant;  // <--see? no ActiveDocument, so you are not 
                      //             modifying the users doc
like image 143
The_Fox Avatar answered Dec 04 '25 20:12

The_Fox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!