共用方式為


AddHandler Statement

Associates an event with an event handler at run time.

AddHandler event, AddressOf eventhandler

Parts

  • event
    The name of the event to handle.

  • eventhandler
    The name of a procedure that handles the event.

Remarks

The AddHandler and RemoveHandler statements allow you to start and stop event handling at any time during program execution.

The signature of the eventhandler procedure must match the signature of the event event.

The Handles keyword and the AddHandler statement both allow you to specify that particular procedures handle particular events, but there are differences. The AddHandler statement connects procedures to events at run time. Use the Handles keyword when defining a procedure to specify that it handles a particular event. For more information, see Handles Clause (Visual Basic).

Note

For custom events, the AddHandler statement invokes the event's AddHandler accessor. For more information on custom events, see Event Statement.

Example

Sub TestEvents()
    Dim Obj As New Class1
    ' Associate an event handler with an event. 
    AddHandler Obj.Ev_Event, AddressOf EventHandler
    ' Call the method to raise the event.
    Obj.CauseSomeEvent()
    ' Stop handling events. 
    RemoveHandler Obj.Ev_Event, AddressOf EventHandler
    ' This event will not be handled.
    Obj.CauseSomeEvent()
End Sub 

Sub EventHandler()
    ' Handle the event.
    MsgBox("EventHandler caught event.")
End Sub 

Public Class Class1
    ' Declare an event. 
    Public Event Ev_Event()
    Sub CauseSomeEvent()
        ' Raise an event. 
        RaiseEvent Ev_Event()
    End Sub 
End Class

See Also

Reference

RemoveHandler Statement

Handles Clause (Visual Basic)

Event Statement

Other Resources

Events (Visual Basic)