AddHandler and RemoveHandler
Updated: August 2008
The AddHandler statement is similar to the Handles clause in that both allow you to specify an event handler. However, AddHandler, used with RemoveHandler, provides greater flexibility than the Handles clause, allowing you to dynamically add, remove, and change the event handler associated with an event. If you want to handle shared events or events from a structure, you must use AddHandler.
AddHandler takes two arguments: the name of an event from an event sender such as a control, and an expression that evaluates to a delegate. You do not need to explicitly specify the delegate class when using AddHandler, since the AddressOf statement always returns a reference to the delegate. The following example associates an event handler with an event raised by an object:
RemoveHandler, which disconnects an event from an event handler, uses the same syntax as AddHandler. For example:
In the following example, an event handler is associated with an event, and the event is raised. The event handler catches the event and displays a message.
Then the first event handler is removed and a different event handler is associated with the event. When the event is raised again, a different message is displayed.
Finally, the second event handler is removed and the event is raised for a third time. Because there is no longer an event handler associated with the event, no action is taken.
Module Module1 Sub Main() Dim c1 As New Class1 ' Associate an event handler with an event. AddHandler c1.AnEvent, AddressOf EventHandler1 ' Call a method to raise the event. c1.CauseTheEvent() ' Stop handling the event. RemoveHandler c1.AnEvent, AddressOf EventHandler1 ' Now associate a different event handler with the event. AddHandler c1.AnEvent, AddressOf EventHandler2 ' Call a method to raise the event. c1.CauseTheEvent() ' Stop handling the event. RemoveHandler c1.AnEvent, AddressOf EventHandler2 ' This event will not be handled. c1.CauseTheEvent() End Sub Sub EventHandler1() ' Handle the event. MsgBox("EventHandler1 caught event.") End Sub Sub EventHandler2() ' Handle the event. MsgBox("EventHandler2 caught event.") End Sub Public Class Class1 ' Declare an event. Public Event AnEvent() Sub CauseTheEvent() ' Raise an event. RaiseEvent AnEvent() End Sub End Class End Module