通过与vb.net的接口捕获事件

时间:2018-01-03 15:31:29

标签: vb.net

我想在表单中添加一个包含简单按钮的用户控件,并从表单中捕获按钮单击事件。这是我的实际代码:

界面:

--no-start

UserControl:

Public Interface IPlugInterface
     Event Test()
End Interface

主要表格:

Public Class Plug

    Implements IPlugInterface

    Private Event Test() Implements IPlugInterface.Test

    Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button.Click
        RaiseEvent Test()
    End Sub

End Class

如何告诉主窗体捕获Plug类发送的“Test”事件?

2 个答案:

答案 0 :(得分:0)

编辑:如评论中所述,首先将Type更改为IPlugInInterface。以下更新的示例:

您可以使用AddHandler或WithEvents连接事件处理程序,如this MSDN article中所述。

AddHandler示例:

Private PlugIn As IPlugInInterface = New Plug()

AddHandler Plugin.Test, AddressOf YourEventHandler

然后:

Private Sub YourEventHandler()
End Sub

WithEvents示例:

Private WithEvents Plugin As IPlugInInterface = New Plug()

然后:

Private Sub YourEventHandler() Handles Plugin.Test
End Sub

答案 1 :(得分:0)

好的,感谢大家在这里修改Form类以使其工作:

Public Class Form

    Private WithEvents PlugInterface As IPlugInterface = New Plug

    Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Me.Controls.Add(PlugInterface)

    End Sub

    Private Sub TestEvent() Handles PlugInterface.Test

        MsgBox("Event !")

    End Sub

End Class

希望我可以通过在启动时将插件控件加载为dll来适应我的实际代码。