Thomas Carlton Thomas Carlton - 3 months ago 6 Question

How do I handle events with interfaces in VB.NET?

I'm new to interfaces and I'm trying to understand how they work.

I wrote the following code, which works properly except the click event which is not firing.

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

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

What's wrong with that code?

(PS: This is just an example allowing me to understand how interfaces work and doesn't have any functional meaning.)


You're missing a single method in the MyButton class to make this work.

You need this:

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

Essentially SimpleButton already has a click method. It's being raised when you click your derived MyButton class. But the Click event on SimpleButton isn't the same event as Click on the IClass interface. You implemented that as click1. So you just need to raise the click1 method when the Click method is raised. Hence the above method.