文档关闭后如何有事件或 运行 方法?

How to have event or run method after the document was Closed?

我有一个 Word 加载项 (VSTO),它将在用户关闭后处理 word 文档。 不幸的是,即使在文档不会真正关闭的情况下,也会引发 DocumentBeforeClose 事件。

Ex:在向用户显示提示用户保存文档的对话框之前引发该事件。询问用户是否要使用“是”、“否”和“取消”按钮进行保存。如果用户选择取消,即使引发了 DocumentBeforeClose 事件,文档仍保持打开状态。 因此,有任何方式或方法可以使 eventMethod 在文档关闭后变为 raisedrun

我试过这样做:

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 事件处理程序确定文档随后是否实际关闭。但是,您可以通过覆盖 File Close 命令获得对关闭过程的完全控制:

  • 向功能区添加命令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];
    }
    

有关如何自定义 Word 命令的完整示例可在 MSDN 上找到:

Temporarily Repurpose Commands on the Office Fluent Ribbon