我的建议是声明一个哨兵标志:
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);
}
}