Search code examples
ms-wordadd-innetoffice

How to listen to new document events in NetOffice Word Addin


I just created a Word Addin Project with NetOffice v1.7.3 to do a proof of concept.

I can see 2 events (OnStartupComplete and OnDisconnection) has been hookup.

<!-- language: c# -->
public class Addin : Word.Tools.COMAddin
{
        public Addin()
        {
            this.OnStartupComplete += new OnStartupCompleteEventHandler(Addin_OnStartupComplete);
            this.OnDisconnection += new OnDisconnectionEventHandler(Addin_OnDisconnection);
        }
}

Do you know how I can Listen to New Document Event, Save Document Event and Close Document Event?

I found this code on the net, but Can't workout how to do it in NetOffice.

<!-- language: c# -->
private void ThisAddIn_Startup(object sender, System.EventArgs e) 
{
    Microsoft.Office.Interop.Word.ApplicationEvents2_Event wdEvents2 = (Microsoft.Office.Interop.Word.ApplicationEvents2_Event) this.Application;
    wdEvents2.NewDocument += new Word.ApplicationEvents2_NewDocumentEventHandler(wdEvents2_NewDocument); 
}

void wdEvents2_NewDocument(Word.Document Doc) 
{
    MessageBox.Show("New Document Fires.", "New Document", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
}

Thanks in Advance
Regards Dat.


Solution

  • private void Addin_OnStartupComplete(ref Array custom)
    {
        Debug.WriteLine(string.Format("Word Addin started in Word Version {0}",Application.Version));
        this.Application.NewDocumentEvent += Application_NewDocumentEvent;
        this.Application.DocumentBeforeCloseEvent += Application_DocumentBeforeCloseEvent;
        this.Application.DocumentBeforeSaveEvent += Application_DocumentBeforeSaveEvent;
        this.Application.DocumentBeforePrintEvent += Application_DocumentBeforePrintEvent;
    }
    
    private void Application_DocumentBeforePrintEvent(Word.Document Doc, ref bool Cancel)
    {
        if (Cancel == false)
        {
            Debug.WriteLine(string.Format("{0} Addin Document {1} is printing", AppName, Doc.Name));
        }
    }
    
    private void Application_DocumentBeforeSaveEvent(Word.Document Doc, ref bool SaveAsUI, ref bool Cancel)
    {
        if (Cancel == false)
        {
            Debug.WriteLine(string.Format("{0} Addin Document {1} is saving", AppName, Doc.Name));
        }
    }
    
    private void Application_DocumentBeforeCloseEvent(Word.Document Doc, ref bool Cancel)
    {
        if (Cancel == false)
        {
            Debug.WriteLine(string.Format("{0} Addin Document is closing.. {1}", AppName, Doc.Name));
        }
    }