I have TWordApplication
named App
component on my form. It's ConnectKind
property is set to ckRunningOrNew
and AutoConnect
property is True
. When my procedure finishes, Word window appears on screen and after doing some tasks I close it. Next call to App
produces the topic error, even if I call Disconnect
.
procedure ReportButtonClick(Sender: TObject);
var
Doc: _Document;
{ Some other variables }
begin
App.Disconnect; // calling after closing produces error
App.Connect;
Doc := App.Documents.Add('path_to_template', EmptyParam, EmptyParam, EmptyParam);
{ Working with Doc }
App.Visible := True;
end;
It seems clear that I shouldn't close Word, but my clients consider keeping Word always opened is not convenient for them. I tried to catch the exception without success.
How should I handle this situation?
Using D7 and Word2007, the following code prevents the user from closing MS Word, either by clicking the [x] on its title bar or Close from its menu:
procedure TDefaultForm.WordApplication1DocumentBeforeClose(ASender: TObject;
const Doc: _Document; var Cancel: WordBool);
begin
Cancel := True;
end;
, though obviously you would want to give the user notice of why this is happening.
However, it will not prevent Word closing if there is no document open in it.
As an alternative to preventing Word from closing, obviously you could disable your app's Word-automating features, complete whatever operation is in progress or close your app entirely. I assume you know how to get at the active document, current text selection, etc in Word.