我在执行某些任务之前检查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;
}
之前有人看过这个问题吗?
有更好的方法可以检查吗?
答案 0 :(得分: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);
}
}