Performing a freeze while checking if Word is visible

I check if Word is actually still displayed before performing certain tasks. The problem is that the execution simply freezes after closing Word 2010 when checking visibility. Not happening since 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; } 

Has anyone seen this problem before?

Is there a better way to test this?

+4
source share
1 answer

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) { // Perform work here. } 

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); } } 
+3
source

All Articles