WithEvents and the Handles Clause
The WithEvents statement and the Handles clause provide a declarative way of specifying event handlers. Events raised by an object declared with the WithEvents keyword can be handled by any procedure with a Handles statement for that event, as shown in the following example:
Dim WithEvents EClass As New EventClass() ' Declare a WithEvents variable. Sub TestEvents() EClass.RaiseEvents() End Sub ' Declare an event handler that handles multiple events. Sub EClass_EventHandler() Handles Eclass.XEvent, Eclass.YEvent MsgBox("Received Event.") End Sub Class EventClass Public Event XEvent() Public Event YEvent() Sub RaiseEvents() 'Raises two events handled by EClass_EventHandler. RaiseEvent XEvent() RaiseEvent YEvent() End Sub End Class
The WithEvents statement and the Handles clause are often the best choice for event handlers, because the declarative syntax they use makes event handling easier to code, read and debug. However, be aware of the following limitations on the use of WithEvents variables:
- You cannot use a WithEvents variable as a generic object variable. That is, you cannot declare it as Object — you must specify the class name when you declare the variable.
- You cannot use WithEvents to declaratively handle shared events, since they are not tied to an instance that can be assigned to a WithEvents variable.
- You cannot create arrays of WithEvents variables.
- WithEvents variables allow a single event handler to handle one or more kind of event, or one or more event handlers to handle the same kind of event.