如何在Vb.Net中引发第三方DLL事件

时间:2018-10-09 01:57:31

标签: vb.net vb6-migration

我已经将少量vb6组件迁移到了点网,以下是对该问题的详细说明。

我有一个包装程序控件,该控件引用了第三方FarPoint控件。在包装控件中,我引发了一个如下所示的事件。

'Declaration of the event
 Public Event ButtonClicked(ByVal Sender As System.Object, ByVal e As 
  AxFPSpreadADO._DSpreadEvents_ButtonClickedEvent) 

 'implementation of the event

Private Sub sprSpread_ButtonClicked(sender As Object, e As AxFPSpreadADO._DSpreadEvents_ButtonClickedEvent) Handles sprSpread.ButtonClicked
    RaiseEvent ButtonClicked(sender, e)
End Sub

因此上述包装器控件在另一个组件之一中被引用(其他组件不过是调用组件)

因此,在调用组件中,我在窗体上添加了包装器控件,并生成了如下所示的ButtonClicked事件。

 Private Sub InstSpread1_ButtonClicked(Sender As Object, e As AxFPSpreadADO._DSpreadEvents_ButtonClickedEvent) Handles InstSpread1.ButtonClicked

End Sub

我收到“未定义AxFPSpreadADO._DSpreadEvents_ButtonClickedEvent类型”错误,并且我也需要在调用组件中引用FarPoint才能消除此错误。

我如何在调用组件中引发ButtonClicked事件而不在调用组件中引用FarPoint?

1 个答案:

答案 0 :(得分:1)

如果我对问题的理解正确,则问题在于您声明的事件使用e参数的第三方类型:

Public Event ButtonClicked(ByVal Sender As System.Object, ByVal e As AxFPSpreadADO._DSpreadEvents_ButtonClickedEvent)

您应该做的是定义自己的继承EventArgs的类:

Public Class ButtonClickedEventArgs
    Inherits EventArgs

    '...

End Class

,然后将其用于您自己的事件。您可以这样操作:

Public Event ButtonClicked(sender As System.Object, e As ButtonClickedEventArgs)

但是您应该这样做:

Public Event ButtonClicked As EventHandler(Of ButtonClickedEventArgs)

然后您应该在自己的组件中完全实现事件模式。这意味着引发事件的专用方法:

Protected Overridable Sub OnButtonClicked(e As ButtonClickedEventArgs)
    RaiseEvent ButtonClicked(Me, e)
End Sub

然后,在第三方组件的事件处理程序中,您可以将数据从收到的AxFPSpreadADO._DSpreadEvents_ButtonClickedEvent对象复制到自己的ButtonClickedEventArgs对象中。我不知道您需要什么属性,所以我只使用示例:

Private Sub sprSpread_ButtonClicked(sender As Object, e As AxFPSpreadADO._DSpreadEvents_ButtonClickedEvent) Handles sprSpread.ButtonClicked
    Dim eventArgs As New ButtonClickedEventArgs

    With eventArgs
        .Name = e.Name
        .Number = e.Number
    End With

    OnButtonClicked(e)
End Sub

编辑:您还可以考虑将复制构造函数添加到自己的事件args类中,这样,如果在多个地方使用复制代码,则无需多次编写复制代码,例如

Public Class ButtonClickedEventArgs
    Inherits EventArgs

    Public Sub New(e As AxFPSpreadADO._DSpreadEvents_ButtonClickedEvent)
        Name = e.Name
        Number = e.Number
    End Sub

    '...

End Class

然后像这样引发事件:

Private Sub sprSpread_ButtonClicked(sender As Object, e As AxFPSpreadADO._DSpreadEvents_ButtonClickedEvent) Handles sprSpread.ButtonClicked
    OnButtonClicked(New ButtonClickedEventArgs(e))
End Sub