My suggestion would be to declare a guard flag:
private bool isWordApplicationOpen;
When you initialize your Application instance, subscribe to Quit and reset the flag from there:
MyApp = new Word.Application(); MyApp.Visible = true; isWordApplicationOpen = true; ((ApplicationEvents3_Event)MyApp).Quit += () => { isWordApplicationOpen = false; }; // ApplicationEvents3_Event works for Word 2002 and above
Then in your loop just check if the flag is set:
while (isWordApplicationOpen) {
Change Given that you only need to wait until the Word application is closed, the following code might be more appropriate:
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); } }
source share