2016-10-03 15 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