共用方式為


How to: Create an Event and Handler (Visual Basic) 

This example defines an event, TimeExpired, and an event handler, HandleTimeExpired, and uses the AddHandler statement to associate them.

Example

Public Event TimeExpired(ByVal Status As String)
Public Sub HandleTimeExpired(ByVal Status As String)
    ' Perform desired processing for when time has expired.
    MsgBox("HandleTimeExpired caught the TimeExpired event" & _
           vbCrLf & "Status = " & Status)
End Sub
Public Sub SetUpEventHandler()
    AddHandler TimeExpired, AddressOf HandleTimeExpired
End Sub

Compiling the Code

This example requires:

  • Access to the members of the System namespace. Add an Imports statement if you are not fully qualifying member names in your code. For more information, see Imports Statement.

  • The Event statement to be at class level and not inside any procedure.

  • The Event statement and both procedures (HandleTimeExpired and SetUpEventHandler) to be defined in the same class or module. Otherwise the AddHandler statement must qualify the event and the handler to the objects in which they are defined.

See Also

Tasks

How to: Raise an Event (Visual Basic)

Reference

Event Statement
AddHandler Statement

Concepts

Events and Event Handlers

Other Resources

Events in Visual Basic