Events 捕获打开的word文件事件

Events 捕获打开的word文件事件,events,file-io,ms-word,Events,File Io,Ms Word,我想制作一个应用程序作为word加载项,在打开文件时更改文件 因此,我在visual Studio中创建了一个word加载项项目,这基本上就是我的代码: namespace WordAddIn1 { public partial class ThisAddIn { private void Application_DocumentOpen(Microsoft.Office.Interop.Word.Document Doc) { MessageBox.S

我想制作一个应用程序作为word加载项,在打开文件时更改文件

因此,我在visual Studio中创建了一个word加载项项目,这基本上就是我的代码:

namespace WordAddIn1
{
    public partial class ThisAddIn
    {
     private void Application_DocumentOpen(Microsoft.Office.Interop.Word.Document Doc)
    {
    MessageBox.Show("doc opened");
    // do my stuff
    }

    #region VSTO generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InternalStartup()
    {
        this.Application.DocumentOpen += new Word.ApplicationEvents4_DocumentOpenEventHandler(Application_DocumentOpen);
    }

    #endregion
}
}
namespace WordAddIn1
{
公共部分类ThisAddIn
{
专用作废应用程序\u DocumentOpen(Microsoft.Office.Interop.Word.Document文档)
{
MessageBox.Show(“打开的文档”);
//做我的事
}
#区域VSTO生成的代码
/// 
///设计器支持所需的方法-不修改
///此方法的内容与代码编辑器一起使用。
/// 
私有void InternalStartup()
{
this.Application.DocumentOpen+=新单词.ApplicationEvents4\u DocumentOpenEventHandler(Application\u DocumentOpen);
}
#端区
}
}

问题是,如果启动一个空的word应用程序(双击word.exe),然后打开一个文档,那么这种方法效果很好,但如果word应用程序与文档打开一起启动(双击.doc文件),则这种方法效果不好。

如果通过双击文档打开word,则不会触发DocumentOpen

要解决此问题,您可以检查文档是否已在Word中打开,如果是,请将文档传递给应用程序\ U DocumentOpen方法


顺便说一句,您似乎已经更改了InternalStartup方法中的代码。如评论所示,您不应该这样做,而应该使用ThisAddIn_启动程序。

以下是执行Abbey建议的代码:

private void ThisAddIn_Startup(object sender, System.EventArgs a)
{
  try
  {
    Word.Document doc = this.Application.ActiveDocument;
    if (String.IsNullOrWhiteSpace(doc.Path))
    {
      logger.Debug(String.Format("Word initialized with new document: {0}.", doc.FullName));
      ProcessNewDocument(doc);
    }
    else
    {
      logger.Debug(String.Format("Word initialized with existing document: {0}.", doc.FullName));
      ProcessOpenedDocument(doc);
    }
  }
  catch (COMException e)
  {
    logger.Debug("No document loaded with word.");
  }
}