Microsoft.Office.Interop error 0x800401E3

1

I am trying to access Microsoft word instance through my service (windows service) but I am getting this error:

Operation unavailable (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE))

I have opened a word document (I can also see WINWORD.EXE in the Task Manager). I am using VS 2010 and MS Office 2003. Here is my code:

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()

If I use this code in a Windows Forms application it works perfect, but doesn't work in a Windows Service. Why is that? Windows Service doesn’t support Microsoft.Office.Interop? If it does work please help?

vb.net
office-interop
asked on Stack Overflow Feb 22, 2013 by MAK • edited Feb 22, 2013 by Daniel A.A. Pelsmaeker

2 Answers

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.

answered on Stack Overflow Feb 22, 2013 by jlvaquero • edited Feb 27, 2013 by jlvaquero
0

Checkout this thread, it might help you:

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

answered on Stack Overflow Mar 18, 2013 by (unknown user) • edited Mar 18, 2013 by Maroun

User contributions licensed under CC BY-SA 3.0