我正在尝试使用 Visio AddAdvise 将事件接收器/处理程序添加到 ActiveDocument,在本例中是从 Visio VSTO 外接程序添加事件接收器/处理程序。
这是班级:
Option Strict On
Imports System.Diagnostics
Imports Microsoft.Office.Interop
Imports Visio = Microsoft.Office.Interop.Visio
Public Class ShapeDeleteEventSink
Implements Visio.IVisEventProc
Public Function VisEventProc(nEventCode As Short, pSourceObj As Object, nEventID As Integer, nEventSeqNum As Integer, ByVal pSubjectObj As Object, ByVal vMoreInfo As Object) As Object Implements Visio.IVisEventProc.VisEventProc
Debug.Print("A shape was deleted event fired")
Return Nothing
End Function
End Class
这是添加事件处理程序/接收器的代码:
Dim EventList As Visio.EventList = Globals.ThisAddIn.Application.ActiveDocument.EventList
Dim ShapeDeleteEventSinkInstance As New ShapeDeleteEventSink
Dim KeyDownEvent As Visio.Event = EventList.AddAdvise(CShort(Visio.VisEventCodes.visEvtCodeShapeDelete), ShapeDeleteEventSinkInstance, "", "A shape was deleted event fired")
代码编译良好。
但是运行它会导致此异常:
System.Runtime.InteropServices.COMException HResult=0x86DB0898
留言=出现异常。来源= 堆栈跟踪:
最后一行:
Dim KeyDownEvent As Visio.Event = EventList.AddAdvise(CShort(Visio.VisEventCodes.visEvtCodeShapeDelete), ShapeDeleteEventSinkInstance, "", "A shape was deleted event fired")
VBA 课程:
Implements Visio.IVisEventProc
Private Function IVisEventProc_VisEventProc( _
ByVal nEventCode As Integer, _
ByVal pSourceObj As Object, _
ByVal nEventID As Long, _
ByVal nEventSeqNum As Long, _
ByVal pSubjectObj As Object, _
ByVal vMoreInfo As Variant) As Variant
Debug.Print ("A shape was deleted!")
End Function
和代码:
Sub AttachShapeDeleteEventSink()
Dim EventList As Visio.EventList
Dim ShapeDeleteEventSinkInstance As New ShapeDeleteEventSink
Dim KeyDownEvent As Visio.Event
Set EventList = Application.EventList
Set KeyDownEvent = EventList.AddAdvise(visEvtCodeShapeDelete, ShapeDeleteEventSinkInstance, "", "This is a shape delete event")
End Sub
但是运行良好。
因为 COM 提供的错误消息很差,我无法真正弄清楚为什么这在 VSTO 加载项中不起作用。
我想使用 AddAdvise 的原因之一是因为我想以一种为我提供 KeyboardEvent 对象的方式“捕获”像 KeyDown 这样的事件。例如,这使我能够轻松捕获用户在 Visio 窗口中按下的快捷键。
感谢您分享您的见解,我对 COM 事件如何在 .NET 互操作中工作还只是初步了解。
您需要将您的 Sink 类标记为可见:
<ComVisible(True)> ' <----------- add this
Public Class ShapeDeleteEventSink
Implements Visio.IVisEventProc
.....
```