如何使用VB.NET中的接口处理事件?

时间:2014-01-20 07:52:08

标签: vb.net interface

我是接口的新手,我正在努力了解它们是如何工作的。

我编写了以下代码,除了未触发的click事件外,它的工作正常。

Public Class Form1
    Dim WithEvents Button As IClass = New MyButton

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Button.Parent = Me
    End Sub

    Public Sub ClickEventHandler(ByVal Sender As Object, ByVal E As EventArgs) Handles Button.Click
        MsgBox("Piwpiw !")
    End Sub
End Class

Public Interface IClass
    Event Click(ByVal Sender As Object, ByVal E As EventArgs)
    Property Parent
End Interface

Public Class MyButton
    Inherits SimpleButton
    Implements IClass

    Public Event click1(ByVal Sender As Object, ByVal E As System.EventArgs) Implements IClass.click

    Public Property Parent1 As Object Implements IClass.Parent
        Get
            Return MyBase.Parent
        End Get
        Set(ByVal value As Object)
            MyBase.Parent = value
        End Set
    End Property
End Class

该代码出了什么问题?

(PS:这只是一个例子,让我了解界面如何工作,没有任何功能意义。)

3 个答案:

答案 0 :(得分:1)

你错过了MyButton课程中的一个方法来完成这项工作。

你需要这个:

Private Sub MyButton_Click(sender As Object, e As System.EventArgs) Handles Me.Click
    RaiseEvent click1(sender, e)
End Sub

基本上SimpleButton已经有了一个点击方法。单击派生的MyButton类时会引发此问题。但Click上的SimpleButton事件与Click界面上的IClass事件不同。您将其实现为click1。因此,您只需在引发click1方法时引发Click方法。因此,上述方法。

答案 1 :(得分:0)

在您的示例代码中,我没有看到引发事件的行。为了能够处理事件处理程序中的事件,你的MyButton类中会有一个引发事件的位置,即:

Public Class MyButton
    Inherits SimpleButton
    Implements IClass

    Public Event click1(ByVal Sender As Object, ByVal E As System.EventArgs) Implements IClass.click

    Public Property Parent1 As Object Implements IClass.Parent
        Get
            Return MyBase.Parent
        End Get
        Set(ByVal value As Object)
            MyBase.Parent = value
        End Set
    End Property

    Public Sub SimulateClick()
        RaiseEvent click1(Me, New System.EventArgs())
    End Sub

End Class

您使用RaiseEvent语句举办活动 当然,上面的示例假设在您的代码中的某个时刻,您调用SimulateClick而不是真正的鼠标单击(这将涉及绘制按钮并对几个鼠标事件做出反应)。引发事件后,将调用您的处理程序。您可以使用Form1_Load方法执行此操作:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Button.Parent = Me
    Button.SimulateClick()
End Sub

我注意到你的MyButton类来自SimpleButton类。您也可以对SimpleButton类中的点击做出反应,并在其中放置RaiseEvent语句,而不是使用SimulateClick方法。

答案 2 :(得分:0)

以下是解决方案:

将MyButton类替换为:

Public Class MyButton
    Inherits SimpleButton
    Implements IClass

    Public Shadows Event click(ByVal Sender As Object, ByVal E As System.EventArgs) Implements IClass.Click

    Public Property Parent1 As Object Implements IClass.Parent
        Get
            Return MyBase.Parent
        End Get
        Set(ByVal value As Object)
            MyBase.Parent = value
        End Set
    End Property

    Public Sub ClickEventHandler(ByVal Sender As Object, ByVal E As EventArgs) Handles     MyBase.Click
        RaiseEvent click(Sender, E)
    End Sub
End Class