WithEvents and the Handles Clause

The WithEvents statement and the Handles clause provide a declarative way of specifying event handlers. An event 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:

' Declare a WithEvents variable. 
Dim WithEvents EClass As New EventClass

' Call the method that raises the object's events. 
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()
    ' RaiseEvents raises both events. 
    Sub RaiseEvents()
        RaiseEvent XEvent()
        RaiseEvent YEvent()
    End Sub 
End Class
' Declare a WithEvents variable. 
Dim WithEvents EClass As New EventClass

' Call the method that raises the object's events. 
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()
    ' RaiseEvents raises both events. 
    Sub RaiseEvents()
        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 an object variable. That is, you cannot declare it as Object—you must specify the class name when you declare the variable.

  • Because shared eventsare not tied to class instances, you cannot use WithEvents to declaratively handle shared events. Similarly, you cannot use WithEvents or Handles to handle events from a Structure. In both cases, you can use the AddHandler statement to handle those events.

  • 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.

See Also

Concepts

AddHandler and RemoveHandler

Reference

Handles

WithEvents

AddHandler Statement