检查Word是否可见时执行冻结

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

//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; } 

有人以前看过这个问题吗?

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

我的建议是宣布一个哨兵旗:

 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); } }