问题
I'm check to see if Word is still visible before I perform certain tasks. The problem is execution just freezes after I close Word 2010 on the check of the visibility. Does not occur with 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;
}
Anyone see this issue before?
Is there a better way to check this?
回答1:
My suggestion would be to declare a sentinel flag:
private bool isWordApplicationOpen;
When initializing your Application instance, subscribe to its Quit event, 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 whether the flag is set:
while (isWordApplicationOpen)
{
// Perform work here.
}
Edit: Given that you only need to wait until the Word application is closed, the following code might be more suitable:
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);
}
}
来源:https://stackoverflow.com/questions/11041494/execution-freezing-while-checking-if-word-is-visible