2012-06-14 36 views
4

我在执行特定任务之前检查Word是否仍然可见。在关闭可见性检查关闭Word 2010后,问题是执行只会冻结。 2007年不会发生。检查Word是否可见时执行冻结

//Initializing Word and Document 

While(WordIsOpen()) 
{ 
} 

//Perform Post Close Tasks 

public bool WordIsOpen() 
{ 
    if(MyApp.Application.Visible)//Execution just freezes at this line after Word is not visible 
      return true; 
    else 
      return false; 
} 

任何人都看过这个问题吗?

有没有更好的方法来检查?

+0

什么类型'MyApp'? –

+0

Microsoft.Office.Interop.Word.Application MyApp – ExceptionLimeCat

+0

这是否仅在调试会话期间发生?我想知道是否winword.exe被连接到VS,它导致它阻止MyApp.Application.Visible。如果您在未经调试的情况下运行项目会发生什么 – Dai

回答

3

我的建议是申报定点标志:从那里

private bool isWordApplicationOpen; 

当初始化你Application例如,订阅其Quit事件,并重置标志:

MyApp = new Word.Application(); 
MyApp.Visible = true; 
isWordApplicationOpen = true; 
((ApplicationEvents3_Event)MyApp).Quit +=() => { isWordApplicationOpen = false; }; 
// ApplicationEvents3_Event works for Word 2002 and above 

然后,在你的循环,只需检查标志是否设置:

while (isWordApplicationOpen) 
{ 
    // Perform work here.  
} 

编辑:既然你只需要等待Word应用程序被关闭,下面的代码可能更适合:

using (ManualResetEvent wordQuitEvent = new ManualResetEvent(false)) 
{ 
    Word.Application app = new Word.Application(); 

    try 
    { 
     ((Word.ApplicationEvents3_Event)app).Quit +=() => 
     { 
      wordQuitEvent.Set(); 
     }; 

     app.Visible = true; 

     // Perform automation on Word application here. 

     // Wait until the Word application is closed. 
     wordQuitEvent.WaitOne(); 
    } 
    finally 
    { 
     Marshal.ReleaseComObject(app); 
    } 
} 
+0

任何想法什么类型的事件引发事件句柄需要? – ExceptionLimeCat

+0

事件委托是['ApplicationEvents4_QuitEventHandler'](http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.applicationevents4_quiteventhandler.aspx),它不接受参数并返回void。 – Douglas

+0

您可以在应用程序结束时处理'.Quit',避免完全旋转等待。 –