After a crash course comes sinking in. This post is a rewrite of yesterdays one
on events in VB.NET. I will concentrate on VB.NET include Daniel and
Chi's comment and after that I will return to my beloved C#.
There are several ways to declare events in VB.NET. The usual one is using the handles keyword. As Daniel pointed out this can link an event handling method to multiple events.
Private Sub MyClick(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click, Button2.Click
ListBox1.Items.Add(String.Format("You clicked {0}", CType(sender, Control).Name))
End Sub
This code will run on a click of button1 as well as a click of
button2. The coupling of the events and handler is declared in the
method signature.
You can also add an eventhandler dynamically form code.
Private Sub MyOtherClick(ByVal sender As Object, ByVal e As EventArgs)
ListBox1.Items.Add("That other click")
End Sub
Private Sub ButtonAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonAdd.Click
AddHandler Button2.Click, AddressOf MyOtherClick
End Sub
Every time ButtonAdd is clicked it will add another event handler to
Button2. When ButtonAdd is clicked 4 times a click of button2 will
result in MyClick being executed first after which MyOtherClick is executed four times in a row.
You can also dynamically remove eventhandlers. This is not limited
to handlers been set dynamically. This removes the event handler which
was set with the handles keyword.
Private Sub ButtonRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonRemove.Click
RemoveHandler Button2.Click, AddressOf MyClick
End Sub
This is no big surprise as reflector had already shown that the Handles keyword translates to an addhandler statement.
Chid pointed out that you do not need to use the WithEvents keyword on an object when it's eventhandlers are set using AddHandler.
Reflector shows that this does not make any difference at all. Just
like handles, withevents is nowhere to be found in the actual generated
code. In fact it all boils down to AddHandler and RemoveHandler which
map to CLR functions. In this post I've shown that you can freely mix
Handles and AddHandler. In last post Reflector showed that there are
some subtltties behind the scenes. These subtleties are enough to make or break the sinking of COM events.
I'm gratefull for VB.NET fixing that for me. And a little sad for C#
not doing what I had hoped to do. After all it's eventhandling syntax
is imho far less confusing.