4

在执行某些任务之前,我会检查 Word 是否仍然可见。问题是我在检查可见性时关闭 Word 2010 后执行就冻结了。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;
}

有人以前见过这个问题吗?

有没有更好的方法来检查这个?

4

1 回答 1

3

我的建议是声明一个哨兵标志:

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);
    }
}
于 2012-06-14T21:34:38.400 回答