Section 8.2. Events and Event Binding


8.2. Events and Event Binding

An event indicates some type of action. This action can be initiated by the user (such as through a mouse click on a command button), by the application code (such as when a change is made to a database record), or by the operating system (such as a timer event). When any action like this occurs, it causes an event to be raised or fired.

Each event has a source. This is the object to which the action is applied, such as the button that was clicked. The source is responsible for alerting the operating system that an event has occurred. It does so by sending an event notification message. For this reason, the event source is often referred to as the sender.

An event often has an event argument, a means of conveying data that pertains to the event. For instance, the press of a keyboard key generates an event that includes event arguments describing the "key code" of the key, and it also includes information on the state of modifier keys (the Shift, Alt, and Ctrl keys). The event argument is part of the message sent by the event source.

An event handler is a procedure that is executed as a result of event notification. The process of associating an event handler with an event is called binding.

In .NET applications, event handlers have a consistent procedure signature.

     Private Sub MyHandler(ByVal sender As System.Object, _       ByVal e As System.EventArgs) 

The sender parameter receives the object that initiated the event, while the e parameter receives the event argument. The System.EventArgs class is a generic event argument class that doesn't convey any specific argument data at all. Those events that have actual event argument data to convey use for e a class derived from System.EventArgs instead.

8.2.1. Control-Related Events

In Windows Forms applications, controls are a veritable smorgasbord of built-in events. For instance, the TextBox control has events associated with changing the text in the TextBox, pressing a key while the TextBox has the focus, clicking or double-clicking on the TextBox with the mouse, moving the mouse over the TextBox, and more.

The Visual Studio IDE can insert an empty event handler for a control into your source code, complete with the proper event parameters. Once you have added the control to the form, access the source code related to the form. Just above the source code editing area are two drop-down lists. The one to the left provides a list of all controls placed on the form. The drop-down list to the right presents all available events that correspond to the control or source selected in the left drop-down list (Figure 8-1). To add a new event handler, select the control from the list of controls, then select the desired event from the list of events.

Figure 8-1. A control event ready to use


Each control has a default event, such as the Click event for Command Buttons. As a shortcut, Visual Studio adds an empty default event for a control to your source code when you double-click on the control. For instance, double-clicking a Command Button produces the following code:

     Private Sub Button1_Click(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles Button1.Click     End Sub 

The Handles clause at the end of the event signature tells the compiler that this procedure is bound to Button1's Click event, Button1.Click. Using this clause, it's possible to assign any procedure to handle an event, as long as it has the right signature. Unlike programming in VB 6, you don't have to name your event handler Control_EventName; you can give it any name you want, as long as you include the Handles clause.

One common event handler can be used for multiple events. Since every event handler has the same argument signature, you can even share a common event handler for events from different controls or system-defined actions. The Handles clause supports a comma-separated list of the events to handle.

     Private Sub ManyButtonClicks(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles Button1.Click, _       Button2.Click, Button3.Click     End Sub 

It's easy to determine which control triggered the event, since the sender parameter contains a reference to the source object. If your event handler processes events that use different derived classes for the e parameter, use the common System.EventArgs class in the parameter signature and then convert the argument to the appropriate class using the CType function. While loading up many events in a single handler is convenient, it should only be done when the events truly result in common functionality. You could send all events for every control on your form to a single handler and use If statements to divide up the work, but that would defeat the elegant event system built into .NET.

8.2.2. WithEvents

Events aren't limited to controls and forms. Your own custom classes can respond to events, too. Events are added to classes using the Event statement and triggered with the RaiseEvent statement.

     Public Class ActiveClass        ' ----- Declare an event.        Public Event AnEvent(ByVal eventData As Integer)        Public Sub RaiseTheEvent(ByVal eventData As Integer)           ' ----- Method to raise the event.           RaiseEvent AnEvent(eventData)        End Sub     End Class 

The class's event is now ready to use. In a Windows Forms class, add a variable of type ActiveClass, including the WithEvents keyword. This keyword enables event handling in the instance of the class.

     Public WithEvents stuffHappens As ActiveClass 

This automatically causes the Visual Studio IDE to add the variable name stuffHappens to the left-hand drop-down list above the code window. Selecting this variable causes the right-hand drop-down list to display the events for the class. In this case, the list contains only the AnEvent event. Selecting this event places an empty event shell in the code editor window (edited here to include a MsgBox function).

     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.

8.2.3. 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 System.Object, _           ByVal e As System.EventArgs)        MsgBox("You found me!")     End Sub 

Add a button named Button1 to the form surface. In the form's Load event, add the code that binds the event to the event handler.

     Private Sub Form1_Load(ByVal sender As Object, _           ByVal e As System.EventArgs) Handles MyBase.Load        ' ----- Bind the event to its handler.        AddHandler Button1.Click, AddressOf Me.LonelyHandler        ' ----- NOTE: The following would also work:        '        '  AddHandler Button1.Click, _        ' New EventHandler(AddressOf Me.LonelyHandler)     End Sub 

Run the program and click the button. It works! To remove an existing handler at runtime, use the RemoveHandler statement with a similar syntax to that of AddHandler.

     RemoveHandler Button1.Click, AddressOf Me.LonelyHandler 

8.2.4. Custom Events

New in 2005. Sometimes there may be a software need to exhibit more control over the lifetime of an event in your classes. The 2005 release of Visual Basic adds features that let you monitor and take action each time a handler is added to an event, each time a handler is removed from an event, and each time an event is raised. This new feature is called custom events.

Using these custom events is easy. In your class definition, simply type:

     accessModifier Custom Event eventName 

and press the Enter key. (accessModifier is one of the standard access modifiers, like Public, that can be used with events.) Visual Studio provides the outline of the custom event.

     accessModifier Custom Event eventName As EventHandler        AddHandler(ByVal value As EventHandler)       ' ----- Special code when adding handlers.        End AddHandler        RemoveHandler(ByVal value As EventHandler)       ' ----- Special code when removing handlers.        End RemoveHandler        RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)       ' ----- Special code when raising the event.        End RaiseEvent     End Event 

These event handlers fire when the specific event-related action happens with the eventName event.




Visual Basic 2005(c) In a Nutshell
Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))
ISBN: 059610152X
EAN: 2147483647
Year: 2004
Pages: 712

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net