< Day Day Up > |
An event is a notification that is given when something specific happens in a program, such as a button being clicked or a text box's value changing. When an event occurs, the type that is giving the notification raises the event, which allows other interested types to handle the event. A type declares an event much in the same way that it declares a subroutine. The following example declares a Click and a Moved event. Class Button Private X, Y As Integer Public Event Click() Public Event Moved(ByVal X As Integer, ByVal Y As Integer) End Class Events are raised by the RaiseEvent statement. The RaiseEvent statement has the same syntax as a method invocation. Sub Move(ByVal X As Integer, ByVal Y As Integer) Me.X = X Me.Y = Y RaiseEvent Moved(X, Y) End Sub Events can be handled in two ways: declaratively and dynamically. Declarative Event HandlingDeclarative event handling is the simplest way to handle events because it allows a type to declare what events it handles, and the compiler takes care of the rest. The first step in declarative event handling is declaring that a field contains something that may raise events. This is done by adding the WithEvents modifier to the beginning of a field declaration. Class Form1 Public WithEvents Button1 As Button End Class Methods can then declare that they handle specific events that are raised by the field. In this example, the Button1_Click method handles the Click event of the Button1 field. Class Form1 Public WithEvents Button1 As Button Public Sub Button1_Click() Handles Button1.Click MsgBox("Button1 was clicked!") End Sub End Class The Handles clause must specify a WithEvents variable followed by an event. The parameters of the method must exactly match the parameters of the event that it wishes to handle. Dynamic Event HandlingSometimes it is not possible or desirable to handle events declaratively. The AddHandler and RemoveHandler statements allow dynamically hooking up to and unhooking from events. Both statements take a delegate (covered later in the chapter) that specifies the method that handles the event. Once a handler has been added to the event, it will continue to be handled until the handler is removed. In the following example, when an instance of Button is created, the code adds a handler for the Click event. When all the Button instances are released, the code removes the handlers from the Click event. Class Form1 Public Buttons As New ArrayList() Public Sub CreateButton() Dim NewButton As New Button() AddHandler NewButton.Click, AddressOf Me.Button_Click Buttons.Add(NewButton) End Sub Public Sub DeleteAllButtons() For Each Button As Button in Buttons RemoveHandler Button.Click, AddressOf Me.Button_Click Next Button End Sub Public Sub Button_Click() MsgBox("Button1 was clicked!") End Sub End Class |
< Day Day Up > |