Event Handling
An event is something that happens as a result of an action. Going back to the car object analogy, imagine that you press the brake (an action). The car stops (an event). If you press the gas pedal (an action), the car moves (an event). An event is always the effect of some action taking place.
Windows Forms have events too, although many of them may not seem very obvious. For example, open and close are two events that occur when you start and stop your application. When you move your mouse cursor into the form, an event takes place, and when your mouse cursor leaves the form, another event occurs. Without events, Windows Forms would be very bland because they would never do anything, no matter what the user tried.
In this section, we'll take a brief look at how events are handled with Windows Forms and .NET. You'll examine events in more detail, and learn how to take advantage of them, in Day 5, "Handling Events in Your Windows Forms."
The Message Loop
Events are wonderful ways of dealing with user input. Let's look at two different application modelsone with events and one without eventsbefore we examine how applications use events.
First, imagine an event-driven application. Event-driven means that the application responds to events caused by user actions. In fact, without these events, the application would do nothing. The events drive the application.
In this model, an application sits around and waits for things to happen. It uses events as its cues to perform actions. For example, a user presses a letter on the keyboard. The application sees that an event has occurred (the key being pressed), performs an action to display that letter on screen, and then waits for another event.
A nonevent-driven application doesn't allow users free reign of the applicationthey can only respond to prompts from the application. With an event-driven application, users can interact with any part of the application they wanted, in any order or time they wanted.
Imagine a nonevent-driven calculator application. When you start the application, it retrieves two values from textboxes, performs the mathematical calculations, and spits out the result. If there are no values in the textboxes, the calculator does nothing. The calculator cannot detect when a number has changed because it isn't aware of events. Anytime you want to change the numbers to calculate a different value, you have to change the numbers first, and then run the application again.
Classic Active Server Pages (in other words, prior to ASP.NET) also work in this way. An ASP application runs when a user requests the page from a browser, spits out the necessary HTML, and then stops. ASPs do not care what happens after that since they don't need to wait for any events. For the ASP application to deal with user input, a user has to enter all values into a Web form before posting it back to the ASP for processing. The ASP has no knowledge other than what is given to it at the start of execution. Figure 3.8 illustrates this process.
Figure 3.8 Nonevent-driven applications involve a three-step process.
Both models have their advantages and disadvantages. Non-event driven applications, once started, can execute without user intervention. Event-driven applications typically require user input, but are often more interactive. Since interactivity is a must with any Windows-based application, all your programs will use the event-driven model.
So how does an application detect events? When a typical Windows application starts, it enters a message loop. A message loop is simply a period of time when the application is waiting for input, or messages from the user. This period continues until the application quits, so it is known as a loop. During this loop, the application does nothing except wait for user input (the period of non-activity is known is idling). When some input is received, the application does some work, and then goes back into the message loop. This cycle continues over and over again until the application is closed.
NOTE
When you provide some input, the Windows OS is the first stop for processing. Windows determines to what application the event applies, and sends it along to the application. These communications are known as Windows messages, hence, the name message loop.
For example, when you first open a Microsoft Word document, nothing happens; Word just idles, waiting for you to type. When you hit a key, an event occurs, a method is executed (to display the character onscreen), and Word goes back into the message loop waiting for more input. Every time you press a key, the message loop stops for a moment to do some processing, and then continues the wait. Figure 3.9 illustrates this cycle.
Figure 3.9 The message loop waits for user input.
Windows Forms are typically the main user interface for your applications. Thus, they'll be dealing with quite a few different events.
Form Events
You've already seen how to handle a few events. In the calculator example from yesterday's lesson, you took advantage of the Button object's Click event. Handling events in Windows Forms, no matter what objects they belong to, is pretty much all the same.
In Day 5 we'll have an in-depth discussion about events, how to handle them, and the differences between various events. For now, though, let's take a look at a few of the 71 events of the Form object.
Controlling Execution
In order to give you, the developer, the most control over your applications, some events fire both before and after an action occurs. For example, when you close your form, the Closing event occurs immediately before the form begins to close, and the Closed event occurs immediately after.
TIP
These types of event names always follow the gerund/pluperfect grammar rules (using ing and ed suffixesClosing and Closed). Not all events come in pairs like this. If you see an ing event name, though, you can be sure there's also an ed event as well, but not the other way around.
Why this two-event-per-action approach? Imagine a grocery store that closes at 10 p.m. Five minutes before the stores actually closes, a message is played over the intercom alerting customers to move to the checkout lanes. This pre-closing event is used to alert customers that something is about to occur. After 10 p.m., the store closes, all customers are kicked out (okay, so it's not a very friendly grocery store), and the doors are locked. This two-step approach allows both the store manager and customers to prepare for the actual closing event.
Windows applications are similar. For example, if a user makes a large number of changes to a word-processing document, and then closes the application using the Close control box but forgets to save the document, what would happen? If you waited for the Closed event to fire before doing anything, it would be too late; the document would have closed and all changes would be lost. With .NET, however, the Closing event fires before closing actually takes place. Here you can prompt the user to save her document before changes are lost, and conditionally save the changes. After the window closes, the Closed event fires, and then you can do whatever other processing you need to (display a message to the user, for instance).
Let's take a look at an example using this two-step process. Listing 3.5 uses the Closing and Closed events of the Form object to illustrate the previous example.
Listing 3.5 Controlling Execution with Events in VB.NET
1: Imports System 2: Imports System.Windows.Forms 3: Imports System.Drawing 4: Imports System.ComponentModel 5: 6: Namespace TYWinForms.Day3 7: 8: public class Listing35 : Inherits Form 9: public sub New() 10: Me.Text = "Event Example" 11: AddHandler Me.Closing, AddressOf Me.ClosingMsg 12: AddHandler Me.Closed, AddressOf Me.ClosedMsg 13: end sub 14: 15: public sub ClosingMsg(Sender as Object, e as CancelEventArgs) 16: Microsoft.VisualBasic.MsgBox("Form closing") 17: end sub 18: 19: public sub ClosedMsg(Sender as Object, e as EventArgs) 20: Microsoft.VisualBasic.MsgBox("Form closed") 21: end sub 22: 23: end class 24: 25: public class StartForm 26: public shared sub Main() 27: Application.Run(new Listing35) 28: end sub 29: end class 30: 31: End Namespace
On line 4 we import a namespace we haven't seen before: System.ComponentModel. This namespace has objects that apply to events that you'll need later in the code. Lines 610 are all standard fare. Lines 11 and 12 use the AddHandler method (which you've seen in Days 1 and 2) to tell the CLR to execute the ClosingMsg and ClosedMsg methods (on lines 15 and 19) when the Closing and Closed events fire respectively. Let's skip down to line 15 and the ClosingMsg method, which is executed when the Closing event fires and before the form actually closes.
First, look at the signature (the first line) of this method. It takes two parameters: an Object and a System.ComponentModel.CancelEventArgs object. You already know what the Object object is. The second parameter is a specialized object that applies only to events, and only to Closing events in particular. It has a special property, Cancel, to interrupt the processthe form's closing in this caseshould that be necessary (like in the word processor example discussed earlier). If you determine that the closing should be stopped (if, for example, the user forgot to save her document), set the Cancel property to true:
e.Cancel = true
The application will stop closing and go back into the message loop.
In this case, we're not concerned about stopping the form from closing. On line 16, we call a method to display a message to the user onscreen. The MsgBox method of the Microsoft.VisualBasic simply presents a pop-up box to the user with the specified text. (Note that instead of using the MsgBox method's full name on line 16, we could have imported the Microsoft.VisualBasic namespace using Imports.)
The ClosedMsg method beginning on line 19 executes after the form has closed. Note that it takes an EventArgs object instead of CancelEventArgs for the second parameter. We'll discuss why in Day 5. This method again calls the MsgBox function to display another message, alerting the user that the form has already closed.
Finally, compile this code from VS.NET or with the following command:
vbc /t:winexe /r:system.dll /r:system.windows.forms.dll /r:system.drawing.dll listing3.5.vb
Recall from Day 2 that the System.ComponentModel namespace is in the System.dll assembly, so we didn't need to reference any new assemblies here. Figure 3.10 shows the output after the Close control box is clicked.
Figure 3.10 The Closing event enables you to intercept the Closed event.
Not all events follow this two-step process, but a few of the Form object's do. Table 3.2 describes these.
Table 3.2 Events with Pre-Cursor Events
Event |
Description |
Closed |
Occurs when a form closes |
InputLanguageChanged |
Occurs when the user attempts to change the language of the form |
Validated |
Occurs when the control's input is validated |
There are a few important events that you should know about when dealing with Windows Forms. You've already learned about Closed, which fires when a form closes. There is also a Load event, which fires immediately before a form is displayed for the first time. The event handler for this event is often a good place to initialize components on your form that you haven't already initialized in the constructor.
The Activated event occurs when your form gains focus and becomes the active applicationit corresponds to the Activate method. Deactivate, on the other hand, is fired when your form is deactivated, that is, when it loses focus or another application become the active one.
Mouse and Keyboard Events
Mouse and keyboard actions are one of the most important types of eventsafter all, those are typically the only forms of user input. As such, there are quite a few events that pertain to these two input devices. Let's begin with the keyboard events.
First is the KeyPress event. This occurs anytime a key is pressed, no matter what key it is (we'll see in a moment how to determine which key it was). If this event doesn't provide enough control, there are also the KeyDown and KeyUp events, which fire when a key is pressed down, and then released, respectively.
These events, due to their nature, provide additional information (such as the specific key that is pressed) that you can use in your application. As such, their event handlers (the methods that execute when the event is fired) are specialized. Declaring these handlers in VB.NET is the same process that you're used to:
'VB.NET AddHandler Form1.KeyPress, AddressOf methodName AddHandler Form1.KeyDown, AddressOf methodName AddHandler Form1.KeyUp, AddressOf methodName
In C#, however, you need to take note of the specialized handlers. Instead of using EventHandler as you did on line 18 of Listing 3.4:
18: btAccept.Click += new EventHandler(this.AcceptIt);
you need to use the KeyPressEventHandler and KeyEventHandler objects:
//C# Form1.KeyPress += new KeyPressEventHandler(methodName) Form1.KeyDown += new KeyEventHandler(methodName) Form1.KeyUp += new KeyEventHandler(methodName)
Like the CancelEventArgs object, the KeyPressEventHandler and KeyEventHandler objects have special properties that aid your application in determining what action caused the event.
The KeyPressEventHandler has two properties: Handled and KeyChar. The first method is simply a true or false value indicating if your method has handled the key press (if it hasn't, the key press is sent to the Windows OS for processing). Most of the time you'll want to set this property to true, unless you specifically want the OS to process that specific key (for example, if you don't need to handle the PrintScrn button, pass it to the OS). KeyChar simply returns the key that was pressed. Listing 3.6 shows an example in VB.NET.
Listing 3.6 Handling Key Presses
1: Imports System 2: Imports System.Windows.Forms 3: Imports System.Drawing 4: Imports System.ComponentModel 5: 6: Namespace TYWinForms.Day3 7: 8: public class Listing36 : Inherits Form 9: public sub New() 10: Me.Text = "Keypress Example" 11: AddHandler Me.KeyPress, AddressOf Me.KeyPressed 12: end sub 13: 14: public sub KeyPressed(Sender as Object, e as KeyPressEventArgs) 15: Microsoft.VisualBasic.MsgBox(e.KeyChar) 16: e.Handled = True 17: end sub 18: 19: public shared sub Main() 20: Application.Run(new Listing36) 21: end sub 22: end class 23: End Namespace
On line 11, you see the event handler, KeyPressed, for the KeyPress event assigned to the event. On line 14 you declare the event handler. Note that it takes a KeyPressEventArgs object parameterthis name corresponds to the KeyPressEventHandler object discussed earlier. On line 15 you simply display the character pressed in a message box, and then set the Handled property to true on line 16. Figure 3.11 shows the output when the capital A key is pressed (Shift+a).
Note, however, that only character, numeric, and the Enter keys fire the KeyPress event. To handle other keys (such as Ctrl, Alt, and the F1F12 function keys), you need to use the KeyUp and KeyDown events. Recall that these events use handlers of type KeyEventHandler, so the second parameter of your event handler methods must be KeyEventArgs:
public sub KeyReleased(Sender as Object, e as KeyEventArgs) 'some code end sub
Figure 3.11 As long as your form has the focus, any key press executes the KeyPressed method.
The KeyEventArgs object has several properties that are useful in determining which key was pressed:
AltTrue or false value that indicates if the Alt key was pressed
ControlIndicates if the Ctrl key was pressed
HandledJust like the KeyPressEventArgs object's Handled property
KeyCodeThe keyboard code for the key pressed
KeyDataThe key data for the key pressed
KeyValueThe keyboard code for the key pressed
ModifiersReturns flags indicating which keys and modifiers (such as Shift, Ctrl, or Alt) were pressed
ShiftIndicates if the shift key was pressed
Every key on the keyboard has unique KeyCode, KeyData, and KeyValue values. The KeyCode and KeyValue properties are typically the same. KeyData is the same as the other two for most keys, but different on modifier keys (see the Keys enumeration in the .NET Framework documentation for a complete reference).
Mouse events occur in a standard order:
MouseEnterWhen the mouse cursor enters the form
MouseMoveWhen the mouse cursor moves over the form
MouseHoverWhen the cursor simply hovers over the form (without moving or clicking)
MouseDownWhen you press a mouse button on the form
MouseUpWhen you release the mouse button
MouseLeaveWhen the mouse cursor leaves the form (moves out from over the form)
The MouseEnter, MouseLeave, and MouseHover events don't provide any special information, and therefore use the standard EventHandler event handler and EventArgs event parameter objects. The MouseMove, MouseDown, and MouseUp events, however, provide special information, and all use the MouseEventHandler MouseEventArgs objects:
public sub MouseClick(Sender as Object, e as MouseEventHandler)
The MouseEventHandler object provides information such as the cursor's exact position onscreen, which button was clicked, and so on. The properties are summarized in Table 3.3.
Table 3.3 MouseEventHandler Properties
Property |
Description |
Button |
Gets which mouse button was pressed (MouseButtons.Left, MouseButtons.Middle, MouseButtons.None, MouseButtons.Right, MouseButtons.XButton1, or MouseButtons.XButton2) |
Clicks |
The number of times the mouse was clicked (an integer value) |
Delta |
The number of detents (or rotational notches) the mouse wheel has moved |
X |
The x screen coordinate of the mouse cursor |
Y |
The y screen coordinate of the mouse cursor |
Drag-and-Drop
Drag-and-drop, a feature introduced with Windows, allows users to take shortcuts with applications by dragging an icon on their computer onto an application. The application takes the file represented by that icon, and does some processing. For example, if you have Microsoft Word open and drag an icon of a Word document into it, Word automatically opens that document for editing. Drag-and-drop also allows you to move and copy files from one folder to another using just the mouse.
Making your Windows Forms applications take advantage of drag-and-drop is a simple process. First, you must set the DragDrop property of the form to true, and then write code for the DragDrop, DragEnter, DragLeave, or DragOver events. The DragEnter, DragLeave, and DragOver events are much like to the similarly named mouse events; they occur when an icon is moved into, out of, or over your form. All of these events use the DragEventHandler object handler, and the DragEventArgs event parameter. Let's take a look at the properties of this parameter.
The AllowedEffect property is an indicator telling you what drag-and-drop actions can take place. For example, if you try to drag and drop a read-only file, you only copy, not move, that file. The actions are indicated by the DragDropEffects enumeration: DragDropEffects.All, DragDropEffects.Copy, DragDropEffects.Link, DragDropEffects.Move, DragDropEffects.None, and DragDropEffects.Scroll. All of these effects correspond to simple Windows functions.
The DragEventArgs.Effect property, then, indicates the effect that is taking place. This is one of the DragDropEffects values listed previously. For example, if the user is dragging a file and holds down the Ctrl key, a copy operation will attempt to be performed, and the Effect property will indicate DragDropEffects.Copy.
The Data property contains the item that is being dragged-and-dropped. This item, whatever it may be, is represented by the IdataObject object, which can represent many different types of objects. See the .NET Framework documentation for more information.
The KeyState property tells you if the Shift, Ctrl, or Alt keys are pressed, just like the Alt, Control, and Shift properties of the KeyUp and KeyDown events.
Finally, the X and Y properties are the same as those for the mouse events; they indicate at which point an item was located at the time of the event.
Changing Events
Any time one of Form's properties changes, there's usually an event associated with it. For example, when you change the Text property of the form, the TextChanged event fires.
Most of the time, these types of events are used for validation routines. For instance, if you want to limit the available fonts for use with your form, you could create a handler for the FontChanged event that overrides invalid user choices.
I won't list all of these events here. You can determine them simply by adding the word "Changed" to each of the properties you learned about earlier todayTextChanged, CursorChanged, VisibleChanged, and so on. All of these methods use a handler of type EventHandler.