我有一个 Word 插件 (VSTO),它将在用户关闭 Word 文档后对其进行处理。
不幸的是,即使文档不会真正关闭,也会引发 DocumentBeforeClose
事件。
例如:在向用户显示对话框提示用户保存文档之前引发该事件。系统会询问用户是否要使用"is"、“否”和“取消”按钮保存。如果用户选择“取消”,则即使引发了 DocumentBeforeClose
事件,文档仍保持打开状态。
因此,有任何方式或方法可以使事件
或方法
在之后引发
或运行
该文件已关闭。
我尝试这样做:
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
Globals.ThisAddIn.Application.DocumentBeforeClose += new Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentBeforeCloseEventHandler(this.Application_DocumentBeforeClose);
// I want some thing like this
Globals.ThisAddIn.Application.DocumentAfterClose += new Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentOpenEventHandler(this.Application_DocumentAfterClose);
}
public void Application_DocumentBeforeClose(Word.Document doc, ref bool Cancel)
{
MessageBox.Show(doc.Path, "Path");
}
// I want some thing like this
public void Application_DocumentAfterClose(string doc_Path)
{
MessageBox.Show(doc_Path, "Path");
}
最佳答案
正如您已经说过的,您无法使用 DocumentBeforeClose
事件处理程序确定文档随后是否实际关闭。但是,您可以通过覆盖文件关闭命令来完全控制关闭过程:
将命令添加到功能区 XML(对于 idMso
FileClose
):<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="OnLoad"> <commands> <command idMso="FileClose" onAction="MyClose" /> </commands> <ribbon startFromScratch="false"> <tabs> <!-- remaining custom UI goes here --> </tabs> </ribbon> </customUI>
在代码中提供相应的回调方法:
public void MyClose(IRibbonControl control, bool cancelDefault) { var doc = Application.ActiveDocument; doc.Close(WdSaveOptions.wdPromptToSaveChanges); // check whether the document is still open var isStillOpen = Application.IsObjectValid[doc]; }
可以在 MSDN 上找到如何自定义 Word 命令的完整示例:
关于c# - 文档关闭后如何有事件或运行方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39834041/