【问题标题】:VSTO Word Application events for new Word documents, windows or instances新 Word 文档、窗口或实例的 VSTO Word 应用程序事件
【发布时间】:2020-06-12 04:23:01
【问题描述】:

在 Windows 10 上 Word 16 (32) 的 VSTO 插件中,我会跟踪每个文档以用于功能区。

我正在使用 VSTO 设计器的应用程序对象。在设计器中它看起来像这样;

Friend WithEvents Application As Microsoft.Office.Interop.Word.Application

然后在 ThisAddinn 我有一个 WithEvents 对象的标准代码。

 Private Sub Application_NewDocument(Doc As Microsoft.Office.Interop.Word.Document) Handles Application.NewDocument

 End Sub

在 ThisAddin 中,我还处理 Application.DocumentOpen

在第一个 Word 实例打开后,如果用户右键单击任务栏中的 Word 图标并选择 Word,则会创建一个新的 Word 文档,但上述 2 个事件不会触发。

我还想指出,从 Word 界面打开文档或单击 word.docx 文件并打开它都可以。只有当您通过右键单击任务栏中的单词图标来打开一个新的工作实例时。

我需要什么活动?

我确实看到 Application.WindowActivate 触发了。我需要使用这个吗?

【问题讨论】:

  • 您在何时何地订阅代码中的事件?
  • 问题已更新。我正在使用带有事件对象的 VSTO 设计器应用程序。
  • 在启动时,您可以检查是否打开了任何文档并模拟触发的 DocumentOpen 事件。似乎可以在订阅之前触发事件。
  • 在启动时我会检查打开的文档。问题是当您从任务栏启动第二个 word 文档时,启动也不会触发。

标签: events ms-word vsto


【解决方案1】:

Application.NewDocument 事件在创建新文档时触发。如果您正在处理嵌入在另一个文档中的文档,则不会发生此事件。您可以尝试使用以下 VBA 宏来确保触发事件:

Public WithEvents appWord as Word.Application 

Private Sub appWord_NewDocument(ByVal Doc As Document) 
 Dim intResponse As Integer 
 Dim strName As String 
 Dim docLoop As Document 

 intResponse = MsgBox("Save all other documents?", vbYesNo) 

 If intResponse = vbYes Then 
 strName = ActiveDocument.Name 
 For Each docLoop In Documents 
 With docLoop 
 If .Name <> strName Then 
 .Save 
 End If 
 End With 
 Next docLoop 
 End If 
End Sub

打开文档时会触发Application.DocumentOpen 事件。

Public WithEvents appWord as Word.Application 

Private Sub appWord_DocumentOpen(ByVal Doc As Document) 
 Dim intResponse As Integer 
 Dim strName As String 
 Dim docLoop As Document 

 intResponse = MsgBox("Save all other documents?", vbYesNo) 

 If intResponse = vbYes Then 
 strName = ActiveDocument.Name 
 For Each docLoop In Documents 
 With docLoop 
 If .Name <> strName Then 
 .Save 
 End If 
 End With 
 Next docLoop 
 End If 
End Sub

在启动时,您可以检查是否打开了任何文档并模拟触发的DocumentOpen 事件。似乎可以在您订阅之前触发事件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    相关资源
    最近更新 更多