VSTO Word应用程序事件,用于新的Word文档、窗口或实例。

问题描述 投票:0回答:1

在Windows 10上的Word 16 (32)的VSTO插件中,我为Ribbon目的跟踪每个文档。

我使用的是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文件并打开都可以。 只有在任务栏中右击word图标打开新的工作实例时,才会出现这种情况。

我需要什么事件?

我确实看到Application.WindowActivate开火。 我需要使用这个吗?

vsto word
1个回答
0
投票

事件 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 事件被发射。似乎在你订阅事件之前就可以发射事件。

© www.soinside.com 2019 - 2024. All rights reserved.