Joe*_*e W 5 .net c# events add-in ms-word
Microsoft Word首次加载时,不会触发NewDocument和DocumentOpen事件.当Word的一个实例已经打开并且打开一个新的或现有的文档时,这些事件就会被激活.
我看到的建议是处理DocumentChange事件(在Word加载时始终触发)而不是其他两个事件.
我的问题是我该如何解决这个问题?DocumentChange事件没有任何参数,那么我怎么知道刚刚打开文档(新文档还是现有文档)?
另外,我已经在DocumentChange事件中有逻辑,并且对新文档和现有文档的处理是不同的,所以我不能只将所有代码都放入事件中.
private void ThisAddIn_Startup(object sender, System.EventArgs a)
{
this.Application.DocumentChange += new ApplicationEvents4_DocumentChangeEventHandler(Application_DocumentChange);
}
private void Application_DocumentChange()
{
// How do I handle NewDocument or DocumentOpen?
}
Run Code Online (Sandbox Code Playgroud)
所以我最终在 ThisAddIn_Startup 中处理加载的文档。如果文档的Path是空字符串,那么我们就知道该文档是新的并且从未保存在本地机器上。否则,我知道它已保存(包括在临时目录中),并且我将其作为现有文档进行处理。
private void ThisAddIn_Startup(object sender, System.EventArgs a)
{
try
{
Word.Document doc = this.Application.ActiveDocument;
if (String.IsNullOrWhiteSpace(doc.Path))
{
ProcessNewDocument(doc);
}
else
{
ProcessDocumentOpen(doc);
}
}
catch (COMException e)
{
log.Debug("No document loaded with word.");
}
// These can be set anywhere in the method, because they are not fired for documents loaded when Word is initialized.
((MSWord.ApplicationEvents4_Event)this.Application).NewDocument +=
new MSWord.ApplicationEvents4_NewDocumentEventHandler(Application_NewDocument);
this.Application.DocumentOpen +=
new MSWord.ApplicationEvents4_DocumentOpenEventHandler(Application_DocumentOpen);
}
Run Code Online (Sandbox Code Playgroud)
正如我对 Deni 的回答的评论所述:在 ThisAddIn.Desiger.cs 的 Initialize() 方法中设置 DocumentOpen 事件处理程序适用于现有文档,但在 Word 打开时初始化的新文档不会调用 NewDocument,因此此解决方案不起作用。因此,我将 DocumentOpen 和 NewDocument 的设置保留在 ThisAddIn_Startup 事件中,否则当文档加载 Word 时也会触发 DocumentOpen。
| 归档时间: |
|
| 查看次数: |
3802 次 |
| 最近记录: |