How to: Handle Events in Visual Basic

The following example defines a class that raises an event when you call the CauseEvent method. This event is handled by an event-handler procedure called EventHandler.

Example

Description

To run this example, add the following code to the form class of a Visual Basic Windows Application project, and call the TestEvents procedure with an integer argument.

Code

Public Class Class1
    ' Declare an event for this class. 
    Public Event Event1(ByVal EventNumber As Integer)
    ' Define a method that raises an event. 
    Sub CauseEvent(ByVal EventNumber As Integer)
        RaiseEvent Event1(EventNumber)
    End Sub 
End Class 

Protected Sub TestEvents(ByVal EventNumber As Integer)
    Dim Obj As New Class1
    AddHandler Obj.Event1, AddressOf Me.EventHandler
    ' Cause the object to raise an event.
    Obj.CauseEvent(EventNumber)
End Sub 

Sub EventHandler(ByVal EventNumber As Integer)
    MsgBox("Received event number " & EventNumber.ToString)
End Sub
Public Class Class1
    ' Declare an event for this class. 
    Public Event Event1(ByVal EventNumber As Integer)
    ' Define a method that raises an event. 
    Sub CauseEvent(ByVal EventNumber As Integer)
        RaiseEvent Event1(EventNumber)
    End Sub 
End Class 

Protected Sub TestEvents(ByVal EventNumber As Integer)
    Dim Obj As New Class1
    AddHandler Obj.Event1, AddressOf Me.EventHandler
    ' Cause the object to raise an event.
    Obj.CauseEvent(EventNumber)
End Sub 

Sub EventHandler(ByVal EventNumber As Integer)
    MsgBox("Received event number " & EventNumber.ToString)
End Sub

See Also

Tasks

How to: Write Event Handlers

Concepts

Events and Event Handlers

Delegates and the AddressOf Operator

AddHandler and RemoveHandler