如何检测 Excel 何时关闭(Office 互操作)
How to detect when Excel has been closed (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;
这是一个 hack,但它对我的目的有用。只保留对 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
}
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;
这是一个 hack,但它对我的目的有用。只保留对 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
}