Execution freezing while checking if Word is Visible

无人久伴 提交于 2019-12-14 03:47:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!