OLE Automation to launch MS Word and bring to front

岁酱吖の 提交于 2019-11-30 09:25:11

问题


What is the "correct" (recommended) method for connecting to a running instance of MS Word and bringing this application to the front? I am doing something like the following from a VBA app:

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

Running on Windows XP with Word 2007, this works most of the time - but periodically, fails to bring the Word window to the front (and instead flashes the minimized icon for Word in the task bar).

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

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

This is not 100% because (as drventure pointed out), if multiple instances of Word are running, you cannot be certain which you will get a handle to. Since when my code launches Word it uses GetObject first and then CreateObject if that fails, as long as there is one instance of Word running to start with, I am OK.


回答1:


Word (and Excel for that matter) will ONLY register the VERY FIRST INSTANCE that loads in the ROT (Running object table).

The ROT is where GETOBJECT "gets the object", so, in certain circumstances, its' possible to have two instances of WinWord.exe loaded, one visible, one not, but the invisible instance is the one registered in the ROT and the visible one is NOT.

That'll get you the behavior you're seeing.

Unfortunately, without some API calls to enumerate all the open windows on the system, you always run the risk that GETOBJECT won't get you the object that you're expecting it to.

There's not much of a way around this.

Besides, you're end goal is a bit suspect anyway.

When you say "What is the "correct" method for connecting to a running instance of MS Word and bringing this application to the front?", what happens if there are 2 or more actual instances of Winword.exe loaded?

Which would you want to "connect" to and bring to the front. that's a roll of the dice anyway, unless you're specifically interested in a particular DOCUMENT window that's open.

From what I understand, Word will register ALL document windows in the ROT, regardless of which instance of Winword it is, so you could theoretically Use Getobject to retrieve a particular DOCUMENT, get the APPLICATION object from the DOCUMENT object and then make it VISIBLE with a NORMAL windowstate.

Here's an example of GetObject for a document

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



来源:https://stackoverflow.com/questions/3860250/ole-automation-to-launch-ms-word-and-bring-to-front

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!