【问题标题】:How to have event or run method after the document was Closed?文档关闭后如何有事件或运行方法?
【发布时间】:2017-02-11 13:00:17
【问题描述】:

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

例如:在向用户显示提示用户保存文档的对话框之前引发该事件。系统会询问用户是否要使用“是”、“否”和“取消”按钮进行保存。如果用户选择取消,即使引发了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");
}

【问题讨论】:

    标签: c# ms-word vsto office-interop word-addins


    【解决方案1】:

    正如您已经说过的,您无法通过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];
      }
      

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

    Temporarily Repurpose Commands on the Office Fluent Ribbon

    【讨论】:

    • 非常感谢您对@DirkVollmar 的帮助。顺便说一句,当用户关闭文档而不保存最后的更改时,对话框仍然会提示用户。所以我想要一个在从这个提示对话框中得到结果后会引发的偶数。
    • @hoss77:很抱歉给您带来了困惑,请参阅我的编辑。
    • 是的,你是对的,我可以在这段代码之后运行我的方法:Application.ActiveDocument.Close(WdSaveOptions.wdPromptToSaveChanges); 但问题仍然存在,因为用户可能会单击取消按钮。我怎么知道呢?或者如何显示此 SaveChanges 框并获取 DialogResult
    • @hoss77:在调用Close之后,您应该能够验证文档是否仍然打开。
    • 我如何验证在调用Close后文档仍然打开。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多