Edit

Share via


How to subscribe to events and handle them in Visual Basic

An event is an action or occurrence — such as a mouse click or a credit limit exceeded — that is recognized by some program component, and for which you can write code to respond. An event handler is the code you write to respond to an event.

In Visual Basic, there are two sides to working with events:

  • Event publishing — Classes declare events and raise them when something interesting happens using the RaiseEvent Statement. This is what actually invokes (calls) the event handlers.
  • Event subscription — You subscribe to events by identifying procedures as handlers for specific events. You can do this either with a Handles clause and a WithEvents variable, or with an AddHandler Statement.

An event handler in Visual Basic is a Sub procedure. Your code doesn't call it directly like other Sub procedures. Instead, event publishers invoke the procedure when the event is raised because the procedure is subscribed to the event.

Using a Handles clause is the default way to subscribe to events in Visual Basic. This is how event handlers are written by the designers when you program in the integrated development environment (IDE). The AddHandler statement is suitable for subscribing to events dynamically at run time.

When the event occurs, Visual Basic automatically calls the event handler procedure. Any code that has access to the event can cause it to occur by executing a RaiseEvent Statement.

You can associate more than one event handler with the same event. In some cases you can dissociate a handler from an event. For more information, see Events.

Subscribe to an event using Handles and WithEvents

  1. Make sure the event is declared with an Event Statement.

  2. Declare an object variable at module or class level, using the WithEvents keyword. The As clause for this variable must specify the class that raises the event.

  3. In the declaration of the event-handling Sub procedure, add a Handles clause that specifies the WithEvents variable and the event name.

  4. When the event occurs, Visual Basic automatically calls the Sub procedure. Your code can use a RaiseEvent statement to raise the event and invoke all subscribed handlers.

    The following example defines an event and a WithEvents variable that refers to the class that raises the event. The event-handling Sub procedure uses a Handles clause to specify the class and event it handles.

    ' Example showing event handling with Handles and WithEvents
    Public Class EventPublisher
        Public Event SomethingHappened()
        
        Public Sub CauseEvent()
            ' Raise the event when something interesting happens
            RaiseEvent SomethingHappened()
        End Sub
    End Class
    
    Public Class EventSubscriber
        ' Declare a WithEvents variable
        Dim WithEvents eventObj As New EventPublisher
        
        ' Handle the event using Handles clause
        Public Sub ProcessHappen() Handles eventObj.SomethingHappened
            ' Insert code to handle somethingHappened event.
            Console.WriteLine("Event handled using Handles clause!")
        End Sub
        
        Public Sub TriggerEvent()
            eventObj.CauseEvent()
        End Sub
    End Class
    

Subscribe to an event using AddHandler

  1. Make sure the event is declared with an Event statement.

  2. Execute an AddHandler statement to dynamically connect the event-handling Sub procedure with the event.

  3. When the event occurs, Visual Basic automatically calls the Sub procedure. Your code can use a RaiseEvent statement to raise the event and invoke all subscribed handlers.

    The following example uses the AddHandler statement in the constructor to associate the OnTimerElapsed procedure as an event handler for a custom timer event.

    ' Example showing event handling with AddHandler
    Public Class Timer
        Public Event TimerElapsed(ByVal message As String)
        
        Public Sub Start()
            ' Simulate timer elapsed
            RaiseEvent TimerElapsed("Timer has elapsed!")
        End Sub
    End Class
    
    Public Class Application
        Private appTimer As New Timer()
        
        Sub New()
            ' Use AddHandler to dynamically associate event handler
            AddHandler appTimer.TimerElapsed, AddressOf OnTimerElapsed
        End Sub
    
        Private Sub OnTimerElapsed(ByVal message As String)
            ' Insert code to handle timer elapsed event
            Console.WriteLine($"Handling timer event: {message}")
        End Sub
        
        Public Sub StartTimer()
            appTimer.Start()
        End Sub
    End Class
    

    You can dissociate an event handler from an event by executing the RemoveHandler statement.

See also