Microsoft.Office.Interop.Word "Cannot activate application"
We are having a problem experienced by a few users when attempting to launch Word from our application via the office interop:
using Word = Microsoft.Office.Interop.Word;
public void ShowWord()
{
_word = new Word.ApplicationClass();
_word.Visible = true;
_word.Activate();
}
If word is not always open a COM exception is thrown stating "Cannot activate application." Adding a Thread.Sleep(1000)
before calling _word.Activate()
prevents this, but obviously is not ideal.
public void ShowWord()
{
_word = new Word.ApplicationClass();
_word.Visible = true;
Thread.开发者_如何学编程Sleep(1000)
_word.Activate();
}
Has anyone seen this before and knows what is causing this and what the right way to fix this is?
We encountered a similar issue, and it seems that Word is asynchonously waiting for the OS to show its window. The way we resolved this is by waiting until the Visible property returns true:
public void ShowWord()
{
_word = new Word.Application();
_word.Visible = true;
System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
while (!_word.Visible && sw.ElapsedMilliseconds < 10000)
{ /* Just Wait!! (at most 10s) */}
_word.Activate();
}
Hope this helps somebody.
Does your application have permission to activate the Word COM object?
Check in DCOMCNFG
what the local activation security requirements are.
However, not sure why your Thread.Sleep(1000)
would allow it to work?
精彩评论