|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
Declares that a procedure handles a specified event.
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.
The signature of the procedure must match the signatures of each event in eventlist.
The Handles keyword and the AddHandler statement both allow you to specify that particular procedures handle particular events, but there are differences. Use the Handles keyword when defining a procedure to specify that it handles a particular event. The AddHandler statement connects procedures to events at run time. For more information, see.
For custom events, the application invokes the event's AddHandler accessor when it adds the procedure as an event handler. For more information on custom events, see.
Public Class ContainerClass ' Module or class level declaration. WithEvents Obj As New Class1 Public Class Class1 ' Declare an event. Public Event Ev_Event() Sub CauseSomeEvent() ' Raise an event. RaiseEvent Ev_Event() End Sub End Class Sub EventHandler() Handles Obj.Ev_Event ' Handle the event. MsgBox("EventHandler caught event.") End Sub ' Call the TestEvents procedure from an instance of the ContainerClass ' class to test the Ev_Event event and the event handler. Public Sub TestEvents() Obj.CauseSomeEvent() 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.