2016-10-03 55 views
2

我有一个Word AddIn(VSTO),它将在用户关闭它之后处理单词文档。 不幸的是,即使文档并非真的关闭,也会引发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"); 
} 

回答

2

正如你已经说了,你不能确定与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]; 
    } 
    

由于全样本如何定制的Word命令可以在MSDN上找到:

Temporarily Repurpose Commands on the Office Fluent Ribbon

+0

非常感谢你对你的帮助@DirkVollmar。 顺便说一下,当他关闭文档而不保存上次更改时,对话框仍然对用户提示。所以我想要一个从提示对话框得到结果后会引发的事情。 – hoss77

+0

@ hoss77:对不起,请看我的编辑。 –

+0

是的你是对的我可以在这段代码后运行我的方法: 'Application.ActiveDocument.Close(WdSaveOptions.wdPromptToSaveChanges);' 但问题仍然存在,因为用户可能他会点击取消按钮。我怎么能知道这一点? 或者我怎样才能显示这个SaveChanges框并获得'DialogResult'。 – hoss77