Section 13.3. Event Handling


13.3. Event Handling

Normally, a user interacts with an application's GUI to indicate the tasks that the application should perform. For example, when you write an e-mail in an e-mail application, clicking the Send button tells the application to send the e-mail to the specified e-mail addresses. GUIs are event driven. When the user interacts with a GUI component, the interactionknown as an eventdrives the program to perform a task. Common events (user interactions) that might cause an application to perform a task include clicking a Button, typing in a TextBox, selecting an item from a menu, closing a window and moving the mouse. A method that performs a task in response to an event is called an event handler, and the overall process of responding to events is known as event handling. Event-handling methods don't return values, so they are implemented as Sub procedures.

13.3.1. A Simple Event-Driven GUI

The Form in the application of Fig. 13.5 contains a Button that a user can click to display a MessageBox. You have already created several GUI examples that execute an event handler in response to clicking a Button. In this example, we discuss Visual Studio's auto-generated code in more depth.

Figure 13.5. Simple event-handling example using visual programming.

  1  ' Fig. 13.5: FrmSimpleEventExample.vb  2  ' Using Visual Studio to create event handlers.  3  Public Class FrmSimpleEventExample  4     ' event handler for btnClickMe's Click event                   5     Private Sub btnClickMe_Click(ByVal sender As System.Object, _  6        ByVal e As System.EventArgs) Handles btnClickMe.Click       7       8        MessageBox.Show("Button was clicked.")                      9     End Sub ' btnClickMe_Click                                    10  End Class ' FrmSimpleEventExample 

Using the techniques presented earlier in the book, create a Form containing a Button. First, create a new Windows application and add a Button to the Form. In the Properties window for the Button, set the (Name) property to btnClickMe and the Text property to Click Me. You'll notice that each variable name we create for a control starts with a three letter code that abbreviates the type of the control. For example, in the variable name btnClickMe, "btn" is an abbreviation for Button. This is a widely used naming practice in the Visual Basic community; however, a name such as clickMeButton would also suffice.

When the user clicks the Button in this example, we want the application to respond by displaying a MessageBox. To do this, you must create an event handler for the Button's Click event. You can create this event handler by double clicking the Button on the Form, which declares the following empty event handler in the program code:

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


By convention, Visual Basic names the event-handler method as controlName_eventName (e.g., btnClickMe_Click). The btnClickMe_Click event handler executes when the user clicks the btnClickMe control.

Each event handler receives two parameters. The firstan Object reference named senderis a reference to the object that generated the event. The second is a reference to an event arguments object (typically named e) of type System.EventArgs (or one of its derived classes). This object contains information about the event that occurred. System.EventArgs is the base class of all classes that represent event information.

Software Engineering Observation 13.1

Event handlers do not return valuesthey are designed to execute code based on an action and return control to the main program.


Good Programming Practice 13.1

Use the event-handler naming convention controlName_eventName so that your method names will be meaningful. Such names tell users what event a method handles for what control. This convention is not required, but it makes your code easier to read, understand, modify and maintain.


To display a MessageBox in response to the event, insert the statement

 MessageBox.Show("Button was clicked.") 


in the event handler's body. The resulting event handler appears in lines 59 of Fig. 13.5. When you execute the application and click the Button, a MessageBox appears displaying the text "Button was clicked".

13.3.2. Another Look at the Visual Studio Generated Code

Visual Studio generates the code that creates and initializes the GUI you build in the GUI design window. This auto-generated code is placed in the Designer.vb file of the Form (FrmSimpleEventExample.Designer.vb in this example). You can open this file by expanding the node for the file you are currently working in (FrmSimpleEventExample.vb) and double clicking the file name that ends with Designer.vb. (You might need to click the Show All Files button first.) Figures 13.6 and 13.7 show this file's contents.

Figure 13.6. First half of the Visual Studio generated code file.


Figure 13.7. Second half of the Visual Studio generated code file.


Now that you have studied classes and objects in detail, this code will be easier to understand. Since this code is created and maintained by Visual Studio, you generally don't need to look at it. In fact, you do not need to understand most of the code shown here to build GUI applications. However, we now take a closer look to help you understand how GUI applications work.

The auto-generated code that defines the GUI is actually part of the Form's classin this case, FrmSimpleEventExample. Line 2 of Fig. 13.6 uses the Partial modifier, which allows this class to be split among multiple files. Line 44 declares as an instance variable of class FrmSimpleEventExample the Button control btnClickMe that we created in Design mode. By default, all variable declarations for controls created through Visual Basic's design window have a Friend access modifier. The code also includes the Dispose method for releasing resources (lines 712) and method InitializeComponent (lines 2143), which contains the code that creates the Button, then sets some of the Button's and the Form's properties. The property values correspond to the values set in the Properties window for each control. Note that Visual Studio adds comments to the code that it generates, as in lines 2426.

When the application begins executing, its Form is created, and the Form's InitializeComponent method is called automatically to establish such properties as the Form's title and size, and the location, size and text for each control. Visual Studio also uses the code in this method to create the GUI you see in design view. Changing the code in InitializeComponent may prevent Visual Studio from displaying the GUI properly.

Error-Prevention Tip 13.1

The code generated by building a GUI in Design mode is not meant to be modified directly, and doing so can make an application function incorrectly. You should modify control properties through the Properties window.


13.3.3. Delegates and the Event-Handling Mechanism

The control that generates an event is known as the event sender. An event-handling methodknown as the event receiverresponds to a particular event that a control generates. When the event occurs, the event sender calls its event receiver to perform a task (i.e., to "handle the event").

The .NET event-handling mechanism allows you to choose your own names for event-handling methods. However, each event-handling method must declare the proper parameters to receive information about the event it handles. Since you can choose your own method names, an event sender such as a Button cannot know in advance which method will respond to its events. So we need a mechanism to indicate which method is the event receiver for an event.

Delegates

Event handlers are connected to a control's events via special objects called delegates. A delegate object holds a reference to a method. The method's signature must match the signature specified by the delegate type's declaration. GUI controls have predefined delegates that correspond to every event they can generate. For example, the delegate for a Button's Click event is of type EventHandler (namespace System). If you look at this type in the online help documentation, you will see that it is declared as follows:

 Public Delegate Sub EventHandler(sender As Object, e  As EventArgs) 


where Object and EventArgs are classes from the System namespace. This uses the Delegate keyword to declare a delegate type named EventHandler, which can hold a reference to a method that does not return a value and receives two parametersone of type Object (the event sender) and one of type EventArgs. If you compare the delegate declaration with btnClickMe_Click's header (Fig. 13.5, lines 56), you will see that this event handler indeed meets the requirements of the EventHandler delegate. Note that the preceding declaration actually creates an entire class for you. The details of this special class's declaration are handled by the compiler.

Indicating the Method That a Delegate Should Call

An event sender uses a delegate object like a method call. Since each event handler must have the same signature as the control's delegate for a particular event, the event sender can simply "call" the appropriate delegate when an event occurs. For example, a Button calls its Click delegate in response to a click. The delegate's job is to invoke the appropriate event-handler method. To enable the btnClickMe_Click method to be called when the user clicks the Button, Visual Basic inserts the clause

 Handles controlName.eventName 


following the event handler's parameter list. For example, Handles btnClickMe.Click in line 6 of Fig. 13.5 indicates that btnClickMe_Click will be called when the user clicks the btnClickMe control (i.e., when the button's Click event occurs). The Handles clause, which is added by Visual Studio when you double click the Button control in Design mode, causes Visual Basic to "register" your event handler as the method to call in response to the event. You can also manually add and remove event handlers at runtime by using the AddHandler and RemoveHandler statements (see msdn2.microsoft.com/en-us/library/6yyk8z93.aspx).

13.3.4. Other Ways to Create Event Handlers

In all the GUI applications you have created so far, you double clicked a control on the Form to create an event handler for that control. This technique creates an event handler for a control's default eventthe event most frequently used with that control. Typically, controls can generate many different types of events, and each type can have its own event handler. For instance, you have already created Click event handlers for Buttons by double clicking a Button in design view (Click is the default event for a Button). However your application can also provide an event handler for a Button's MouseHover event, which occurs when the mouse pointer remains positioned over the Button. We now discuss how to create an event handler for an event that is not a control's default event.

Using the Properties Window to Create Event Handlers

You can create additional event handlers through the Properties window. If you select a control on the Form, then click the Events icon (the lightning bolt icon in Fig. 13.8) in the Properties window, all the events for that control are listed in the window. You can double click an event's name to display the event handler in the editor. If the event handler does not already exist, it will be created. You can also select an event, then use the drop-down list to its right to choose an existing method that will be used as the event handler for that event. The methods that appear in this drop-down list are the class's methods that have the proper signature to be an event handler for the selected event. You can return to viewing the properties of a control by selecting the Properties icon (Fig. 13.8).

Figure 13.8. Viewing events for a Button control in the Properties window.


13.3.5. Locating Event Information

Read the Visual Studio documentation to learn about the different events raised by a control. To do this, select Help > Index. In the window that appears, select .NET Framework in the Filtered by drop-down list and enter the name of the control's class in the Index window. To ensure that you are selecting the proper class, enter the fully qualified class name as shown in Fig. 13.9 for class System.Windows.Forms.Button. Once you select a control's class in the documentation, a list of all the class's members is displayed. This list includes the events that the class can generate. In Fig. 13.9, we scrolled to class Button's events. Click the name of an event to view its description and examples of its use (Fig. 13.10). Note that the Click event is listed as a member of class Control, because class Button's Click event is inherited from class Control.

Figure 13.9. List of Button events.


Figure 13.10. Click event details.




Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

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