我正在创建一个vsto excel加载项,我正在尝试找到一种方法来更改当前功能或添加在当前电子表格按下关闭窗口按钮时调用函数的功能。有谁知道这是可能的还是有任何建议?到目前为止,我还没有找到任何东西。
答案 0 :(得分:0)
Workbook类有一个名为BeforeClose的事件,您可以使用该事件来检测何时关闭工作簿。您还可以使用此事件通过将Cancel参数设置为true来阻止它被关闭。
要在当前工作簿上检测此事件,您必须在当前工作簿上附加BeforeClose事件的事件处理程序。
最简单的方法是在引发Application.WorkbookActivate时将事件处理程序附加到BeforeClose事件。并将其从以前活动的工作簿中分离出来。
e.g。
private Workbook _activeWorkbook = null;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
Application.WorkbookActivate += Application_WorkbookActivate;
// Attach to the BeforeClose event on the Workbook that
// was created when Excel started
_activeWorkbook = Application.ActiveWorkbook;
if (_activeWorkbook != null)
{
_activeWorkbook.BeforeClose += ActiveWorkbook_BeforeClose;
}
}
private void Application_WorkbookActivate(Microsoft.Office.Interop.Excel.Workbook Wb)
{
if (_activeWorkbook != null)
{
_activeWorkbook.BeforeClose -= ActiveWorkbook_BeforeClose;
Marshal.ReleaseComObject(_activeWorkbook);
}
_activeWorkbook = Wb;
_activeWorkbook.BeforeClose += ActiveWorkbook_BeforeClose;
}
private void ActiveWorkbook_BeforeClose(ref bool Cancel)
{
Cancel = MessageBox.Show("Do you want to close the workbook?", "Close Workbook", MessageBoxButtons.YesNo) != DialogResult.Yes;
}
因此,如果要在当前电子表格中按下关闭窗口按钮时更改当前功能或添加调用函数的功能,请在ActiveWorkbook_BeforeClose方法中添加代码。