Visual Basic Language Reference  

Handles

The Handles keyword is used to declare that a procedure handles a specified event.

proceduredeclaration Handles event

Parts

proceduredeclaration
The Sub procedure declaration for the procedure that will handle the event.
event
The name of the event being handled. This event must be raised by either the base class for the current class, or by an object declared using the WithEvents keyword.

Remarks

Use the Handles keyword at the end of a procedure declaration to cause it to handle events raised by an object variable declared using the WithEvents keyword. The Handles keyword can also be used in a derived class to handle events from a base class.

Example

WithEvents Obj As New Class2()   ' Module or class level declaration.
Sub EventHandler() Handles Obj.Ev_Event
   MsgBox("EventHandler caught event.")   ' Handle the event.
End Sub

Public Class Class2
   Public Event Ev_Event()    ' Declare an event.
   Sub CauseSomeEvent()
      RaiseEvent Ev_Event()   ' Raise an event.
   End Sub
End Class

Public Class Class3
   Sub TestEvents()
      Obj.CauseSomeEvent()   ' Ask the object to raise an event.
   End Sub
End Class

The following example demonstrates how a derived class can use the Handles statement to handle an event from a base class.

Public Class BaseClass
   Event Ev1() ' Declare an event.
End Class
Class DerivedClass
   Inherits BaseClass
   Sub TestEvents() Handles MyBase.Ev1
      ' Add code to handle this event.
   End Sub
End Class

See Also

WithEvents | AddHandler Statement | RemoveHandler Statement | Events and Event Handlers