如何在NetOffice Word Addin中收听新文档事件

时间:2016-05-18 07:35:58

标签: ms-word add-in netoffice

我刚刚使用NetOffice v1.7.3创建了一个Word Addin项目来进行概念验证。

我可以看到2个事件(OnStartupComplete和OnDisconnection)已经连接。

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

您知道如何收听新文档事件,保存文档事件和关闭文档事件吗?

我在网上找到了这个代码,但是无法在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); 
}

先谢谢你 问候Dat。

1 个答案:

答案 0 :(得分:1)

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));
    }
}