如何检测Excel何时关闭(Office interop)

时间:2016-10-26 12:55:23

标签: c# excel ms-word office-interop

Microsoft Word互操作提供Quit事件以检测用户何时关闭它:

var word = new Microsoft.Office.Interop.Word.Application();
var events = (Microsoft.Office.Interop.Word.ApplicationEvents4_Event)word;
events.Quit += Word_Quit;

Microsoft Excel有类似的东西吗?我找到了类似的界面,但不幸的是没有Quit事件:

var excel = new Microsoft.Office.Interop.Excel.Application();
var events = (Microsoft.Office.Interop.Excel.AppEvents_Event)excel;

1 个答案:

答案 0 :(得分:0)

这是一个黑客,但它适用于我的目的。只需保留对Excel / Word文档的引用,并定期尝试访问简单属性。如果失败,文档很可能已经关闭:

try
{
    if (this.workbook != null)
    {
        var count = this.workbook.Worksheets.Count;
    }
    else
    {
        var count = this.wordDocument.Content.StoryLength;
    }
}
catch
{
    // Office has been closed
}
相关问题