OLE Automation launches MS Word and brings to the fore

What is the “correct” (recommended) method for connecting to an executable instance of MS Word and bringing this application to the forefront? I am doing something like the following from a VBA application:

... objWord = GetObject ("Word.Application") if (objWord is nothing) then objWord = CreateObject("Word.Application") end if objWord.Activate() objWord.Visible = true objWord.WindowState = 1 'maximized ... 

It works in Windows XP with Word 2007, it works most of the time - but occasionally it is not possible to bring the Word window to the foreground (and instead the icon with the minimum value for Word on the taskbar blinks).

NOTE I partially resolved this problem using the FindWindow Win API call:

 hwnd = FindWindow("OpusApp", vbNullString) If hwnd > 0 Then SetForegroundWindow (hwnd) end if 

This is not 100%, because (as indicated in drventure), if multiple instances of Word are running, you cannot be sure what you will be referred to. Since when my code launches Word, it first uses GetObject and then CreateObject, if that fails, if there is one instance of Word that starts to start, I'm fine.

+3
source share
1 answer

Word (and Excel, for that matter) will ONLY register the VERY FIRST INSTANCE, which is loaded into the ROT (desktop table).

ROT is where GETOBJECT "receives the object", so under certain circumstances it "can load two instances of WinWord.exe, one visible, one not, but an invisible instance - one that is registered in ROT and visible - NOT.

This will give you the behavior you see.

Unfortunately, without some API calls to list all open windows in the system, you always risk that GETOBJECT will not give you the object that you expect from it.

Not much here.

In addition, you end up suspecting a little.

When you say “What is the“ correct ”method to connect to a running instance of MS Word and bring this application to the forefront?”, What happens if 2 or more actual instances of the downloaded Winword.exe file are loaded?

What would you like to “connect” and bring to the fore. that a roll of dice in any case, unless you are specifically interested in a separate document window that opens.

From what I understand, Word will register ALL document windows in ROT, no matter what instance of Winword it is, so theoretically you could use Getobject to retrieve a specific DOCUMENT, get the APPLICATION object from the DOCUMENT object and then do this VISIBILITY with NORMAL windowstate.

Here is a GetObject example for a document

http://support.microsoft.com/kb/307216

+2
source

All Articles