
Events and Event Binding | 119
Delegates and
Events
This is the Title of the Book, eMatter Edition
Copyright © 2006 O’Reilly & Associates, Inc. All rights reserved.
Private Sub stuffHappens_AnEvent(ByVal eventData As Integer) _
Handles stuffHappens.AnEvent
MsgBox("Event raised: " & eventData)
End Sub
Some code added to a button’s Click event completes the demonstration.
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
' ----- Raise an event in an ActiveClass instance.
stuffHappens = New ActiveClass( )
stuffHappens.RaiseTheEvent(7)
End Sub
The WithEvents keyword approach to event handling has one slight drawback in
that the
New keyword cannot be used in the declaration, as in:
' ----- This doesn't work.
Public WithEvents stuffHappens As New ActiveClass
Thus, the object must be instantiated separately from the variable declaration, as
demonstrated in the example.
AddHandler and RemoveHandler
Binding events to event handlers with the Handles keyword is easy, but it’s not the
only way to use events. Visual Basic also includes the
AddHandler statement (and its
counterpart, the
RemoveHandler statement) to bind an event to an event handler at
runtime instead of at design time. For instance, you could connect a button’s Click
event to a handler at runtime. First, create the event handler in the form’s code.
Private Sub LonelyHandler(ByVal sender As ...