Toby Allen
Toby Allen

Reputation: 11213

Preventing a hidden instance of Word from stealing focus from my application

I have a Delphi ActiveX that called from a macro on a Word template. It manages documents and opens them in the word instance.

In part of it I use another hidden word instance to generate text previews of the documents to be shown before opening.

TBlobField(fieldbyname( cdocumentDatafield)).SaveToFile(tmpDocPath +HTMLDOCPREVIEWFILE);
DMMain.WordApphtml.documents.Open(tmpDocPath +HTMLDOCPREVIEWFILE);
DMMain.WordApphtml.activedocument.Saveas(tmpDocPath +HTMLPREVIEWFILE, wdFormatText);
DMMain.WordApphtml.activedocument.Close;

The variable is created like this

dmmain.Wordapphtml :=  CreateOleObject('Word.Application');
dmmain.WordApphtml.Visible := false;

Basically the code dumps the file from the database, opens the file in my hidden word instance and saves it as a text file which I can then load.

My problem is that after the text file is generated and I load it, my application has lost focus (its still displayed on top of word, but if I hit a key nothing happens). I assume the invisible app now has focus

Upvotes: 0

Views: 475

Answers (2)

Daniel
Daniel

Reputation: 1051

Easiest way is to just "steal" the focus back...

SetActiveWindow(Application.Handle)

or if you want a specific form to be active

SetActiveWindow(MySpecialForm.Handle)

Upvotes: 2

Toby Allen
Toby Allen

Reputation: 11213

In the end I fixed it by clicking on my form via code. Using this SO hack to get there.

    SavedGridPosition :=  THackDBGrid(DBGridRecipes).cellRect(0,THackDBGrid(DBGridRecipes).row);
    SavedGridPoint.X  := SavedGridPosition.Left;
    SavedGridPoint.Y :=  SavedGridPosition.Top;

    SavedGridPoint := ClientToScreen(SavedGridPoint) ;

    SavedGridPoint.X := savedgridpoint.x + dbgridRecipes.Left;

then after I had created my preview document I call a click event.

setcursorpos(SavedGridPoint.X, savedgridpoint.Y);
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);

Seems to work

Upvotes: 0

Related Questions