1

我正在尝试通过我的服务(Windows 服务)访问 Microsoft Word 实例,但出现此错误:

操作不可用(HRESULT 异常:0x800401E3 (MK_E_UNAVAILABLE))

我打开了一个word文档(我也可以在任务管理器中看到WINWORD.EXE)。我正在使用 VS 2010 和 MS Office 2003。这是我的代码:

Dim fs As New FileStream("D:\log.txt", FileMode.OpenOrCreate, FileAccess.Write)
Dim sw As New StreamWriter(fs)
sw.BaseStream.Seek(0, SeekOrigin.End)
Dim wordapp As Word.Application
wordapp = Marshal.GetActiveObject("Microsoft.Office.Interop.Word.Application")
For Each doc As Word.Document In wordapp.Documents
    sw.WriteLine(doc.FullName.ToString() + "\n" +
    doc.ActiveWindow.WindowState.ToString())
Next
sw.Flush()
sw.Close()

如果我在 Windows 窗体应用程序中使用此代码,它可以完美运行,但在Windows Service中不起作用。这是为什么?Windows 服务不支持Microsoft.Office.Interop?如果它确实有效,请帮忙?

4

2 回答 2

2

Maybe this is the reason your code works in a Windows Forms:

Although the Office application is running, it might not be registered in the Running Object Table (ROT). A running instance of an Office application must be registered in the ROT before it can be attached to using GetObject (Visual Basic) or GetActiveObject (Visual C++).

When an Office application starts, it does not immediately register its running objects. This optimizes the application's startup process. Instead of registering at startup, an Office application registers its running objects in the ROT once it loses focus. Therefore, if you attempt to use GetObject or GetActiveObject to attach to a running instance of an Office application before the application has lost focus, you might receive one of the errors above.

Your form has the focus so the Office app lost focus and register in ROT. With windows service Office doesn't loose the focus.

Just use some interop winapi code to change focus or minimeze office (or all) windows in the desktop. But remember, register in ROT (even when office lost focus) is not determinist, so you must do a loop trying GetObject until you recibe the right response.

于 2013-02-22T11:19:45.737 回答
0

查看此线程,它可能会对您有所帮助:

http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/e6b94d33-fee9-4696-8618-3e798d329d80

于 2013-03-18T12:16:34.380 回答