You are on page 1of 58

12

Graphical User Interface
Concepts: Part I

Objectives
• To understand the design principles of graphical user
interfaces.
• To be able to build graphical user interfaces.
• To understand the packages containing graphical user
interface components and event handling classes and
interfaces.
• To create and manipulate buttons, labels, lists, text
fields, scrollbars and panels.
• To understand mouse events and keyboard events.
… the wisest prophets make sure of the event first.
Horace Walpole
Do you think I can listen all day to such stuff?
Lewis Carroll
Speak the affirmative; emphasize your choice by utter
ignoring of all that you reject.
Ralph Waldo Emerson
You pays your money and you takes your choice.
Punch
Guess if you can, choose if you dare.
Pierre Corneille
All hope abandon, ye who enter here!
Dante Alighieri
Exit, pursued by a bear.
William Shakespeare

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/5/01

582 Graphical User Interface Concepts: Part I Chapter 12

Outline
12.1 Introduction
12.2 Windows Forms
12.3 Event Handling Model
12.3.1 Basic Event Handling
12.3.2 Creating New Events
12.3.3 Event Example: A Fire Department
12.4 Labels, Buttons and TextBoxes
12.5 GroupBoxes and Panels
12.6 CheckBoxes and RadioButtons
12.7 Scrollbars
12.8 PictureBoxes
12.9 Mouse Event Handling
12.10 Keyboard Event Handling
Summary • Terminology • Self-Review Exercises • Answers to Self-Review Exercises • Exercises

12.1 Introduction
A graphical user interface (GUI) presents a pictorial interface to a program. A GUI (pro-
nounced “GOO-EE”) gives a program a distinctive “look” and “feel.” By providing differ-
ent applications with a consistent set of intuitive user interface components, GUIs allow the
user to spend less time trying to remember which keystroke sequences do what and spend
more time using the program in a productive manner.
Look-and-Feel Observation 12.1
Consistent user interfaces also enable a user to learn new applications faster. 12.1

As an example of a GUI, Fig. 12.1 contains a Internet Explorer window with some of
its GUI components labeled. In the window, there is a menu bar containing menus (File,
Edit, View, etc.). Below the menu bar there is a set of buttons that each have a defined task
in Netscape Communicator. Below the buttons there is a text field in which the user can
type the name of the World Wide Web site to visit. To the left of the text field is a label that
indicates the purpose of the text field. The menus, buttons, text fields and labels are part of
Netscape Communicator’s GUI. They enable the user to interact with the Communicator
program. In this chapter and the next, we will demonstrate these GUI components.
GUIs are built from GUI components (sometimes called controls or widgets—short-
hand notation for window gadgets). A GUI component is an object with which the user
interacts via the mouse or the keyboard. Several common GUI components are listed in
Fig. 12.2. In the sections that follow, we discuss each of these GUI components in detail.
In the next chapter, we discuss more advanced GUI components.

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/5/01

Chapter 12 Graphical User Interface Concepts: Part I 583

Button Label Menu Menu bar Textbox

Fig. 12.1 A sample Internet Explorer window with GUI components.

Component Description

Label An area where uneditable text or icons can be displayed.
Textbox An area in which the user inputs data from the keyboard. The area can
also display information.
Button An area that triggers an event when clicked.
CheckBox A GUI component that is either selected or not selected.
ComboBox A drop-down list of items from which the user can make a selection
by clicking an item in the list or by typing into the box, if permitted.
ListBox An area where a list of items is displayed from which the user can
make a selection by clicking once on any element in the list. Multiple
elements can be selected.
Panel A container in which components can be placed.

Fig. 12.2 Some basic GUI components .

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/5/01

584 Graphical User Interface Concepts: Part I Chapter 12

12.2 Windows Forms
Windows Forms (previously called WinForms) are used to create the GUI, the graphical
interface to the program. A form is a graphical element that appears on the desktop. This
form can be a dialog box, a window or an MDI window (multiple document interface win-
dow, discussed in the next chapter). In C#, a component is a class that implements the
IComponent interface, which defines the behavior it must implement. A control is a
graphical component, such as a button. Although most components are controls, there are
a few notable exceptions, such as timers. A timer generates events (covered in the next sec-
tion) at a regular interval, but the component itself cannot be seen. Non-control components
are usually referred to as components. Figure 12.3 displays the Windows Forms controls
and components, all available from the toolbox. The pointer is not a component—it allows
the programmer to use the mouse cursor instead of selecting an item to add.

Fig. 12.3 Components and controls for Windows Forms.

When interacting with windows, we say that the active window has the focus. The
active window is the frontmost and has a blue title bar.
An empty form cannot interact with the user (except to be resized or closed). It must
use controls, perhaps with the help of non-visible components. The form acts as a container
for the components that are added. In C#, controls must be explicitly added to the form
using code. Visual Studio.NET writes this code for us when we insert controls from the

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/5/01

Chapter 12 Graphical User Interface Concepts: Part I 585

toolbox. When the user interacts with a control it generates an event (discussed in the next
section). This event can trigger methods that respond to the user’s actions.
Every class in this chapter is in the System.Windows.Forms namespace. It must
be stressed that all forms, components and controls are classes. Class Form, the basic
window used by Windows applications, is fully qualified as System.Win-
dows.Forms.Form. Likewise, class Button is actually System.Win-
dows.Forms.Button.
The general design process for creating Windows applications involves creating a
Windows Form, setting its properties, adding controls, setting their properties and config-
uring the event handlers. Figure 12.4 lists common Form properties and events.

Form events and
properties Description / Delegate and Event Arguments

Common Properties
AcceptButton Sets the button that will be clicked when Enter is pressed.
AutoScroll Sets whether scrollbars appear if needed (boolean).
BackColor Background color of form.
CancelButton Sets the button that will be clicked when the Escape key is pressed.
FormBorderStyle Border of the form (none, single, 3D, sizable, etc.).
Font Default font of controls added to the form.
IsMdiContainer Sets whether form can have multiple documents (see Chapter 13).
Text Title bar of the form.
Common Events Forms are not usually used with events, but rather to hold controls.
Load EventHandler, EventArgs.
Occurs before form is loaded. Default when component double-
clicked in designer.

Fig. 12.4 Form properties and events.

Luckily, Visual Studio.NET generates most of our code when we create controls and
event handlers. Most tasks can be done graphically, by dragging and dropping components
onto the form and setting properties using windows. This is a great example of visual pro-
gramming: The IDE handles the messy details and the programmer concentrates on logic
(the event handlers).

12.3 Event Handling Model
GUIs are event driven (i.e., they generate or raise events when the user of the program in-
teracts with the GUI). Some common interactions are moving the mouse, clicking the
mouse, clicking a button, typing in a text field, selecting an item from a menu, closing a
window, etc. When a user interaction occurs an object generates an event. The event infor-
mation is then passed to event handlers, or methods that act in response. An example of this

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/5/01

Instead. In the above methods the italic words can be changed.5 Event handling model using delegates. EventArgs e ) { Console. Once an event is raised. the first parameter should be object sender. Events in C# are based on the idea of delegates. Each method in the list must return void and have the same signature (same parameter and return types). passes it to the form’s event handler and the event handler changes the color of the form. every method in the delegate must have the same signature.1 Basic Event Handling In many cases the programmer will not have to create his own events. in general: void MyControl_EventName( object sender. All we must do is create our event handler and register it with the delegate. 12. 7/5/01 . or perhaps class Even- tArgs itself. For this reason. and the second parameter is the event argument class (usually ending with EventArgs). delegates act as an intermediate step between the object cre- ating (raising) the event and the method handling it (Fig. Inc. as well as the code to call it when the event is raised. EventArgs e ) { // event handling code } Every event handler is passed two objects: The object that raised the event (sender) and the event arguments (e). because they are all being passed the same information. Suppose our component has the event name EventName." ). 12. information about the event. he will sim- ply handle the events generated by prepackaged controls such as buttons and scrollbars. The button generates an event. which means they contain a list of methods that they call. every method in the delegate is called. the return type should be void. Event delegates are multicast (class Multi- castDelegate). Handler 1 for event E Object A raises event E Delegate for event E Handler 2 for event E Handler 3 for event E Fig. All Rights Reserved.3. The delegate object has already been created. } © Copyright 1992–2002 by Deitel & Associates. Delegates (discussed in Chapter 10) are objects containing a method they can call. The event arguments will be in a class derived from class EventArgs (namespace System). To create our event handler we must find the signature of the delegate. 12. In the event handling model.586 Graphical User Interface Concepts: Part I Chapter 12 would be a form that changes color when a button is clicked. Then the format of the event handler is. but the text in a regular font should not be.5). Thus. An example event handler for the Click event would be: void MyForm_Click( object sender.WriteLine( "Object was clicked.

NET can actually create most of the event registration code for us. Inc. click the Events icon (the yellow lightning bolt) in an object’s Properties window. This window is a con- venient way to access.EventName.Chapter 12 Graphical User Interface Concepts: Part I 587 The event arguments for the click event is simply the class EventArgs. We can add more event handlers using similar statements. The += operator keeps the previous delegate and adds the new one. 12. This returns a delegate object initialized with method meth- odName. The left panel lists the events that the object can generate. Each object has a delegate reference for each of its events. The differ- ences between the various EventArgs classes are discussed in the following sections.1 Do not have multiple event handlers (registered for the same event) that depend on the order they are called. 12. we write new Delegate- Name( methodName ). To register and define an event handler visually. so we only have to implement the event handler. modify and create event handlers for a component. The delegate reference name is the event name. The name of the delegate itself is often EventNam- eEventHandler. 7/5/01 .1 We will also give the name of the delegate when we cover an event. Given an object (objectName) that can raise an event (EventName) with delegate (DelegateName) and a user-defined event handler (MyEventHandler). Visual Studio. Each of the event handlers is called when the event occurs.6. To remove a handler from an event we use the -= operator to subtract the method from the delegate object. To create a new delegate object. All Rights Reserved. We can use the += operator to add methods to the delegate reference. then there is a field objectName. Multicasting is the ability to have multiple han- dlers per event. The drop down arrow indicates that multiple handlers can be registered for one event. if we are handling event EventName for object objectName. The right panel lists the registered event han- dlers for the corresponding event–it is initially empty. After creating the event handler we must register it. register the first event handler and have it call the others in order.EventName += new DelegateName( MyEventHandler ). because “event handler” refers to a method and EventHandler refers to a delegate reference. We must create a new delegate object for the method we want to register (first explained in Chapter 10). but their order is not known. we can reg- ister it by writing: objectName. as in Fig. The terminology is a bit tricky. or attach it to the delegate. Good Programming Practice 12. passing the sender and event arguments. © Copyright 1992–2002 by Deitel & Associates. If the order is important. We do not have to explicitly register the event or define the parameters for the event handler. Thus.

6 The events section of the Property window.7 Empty event handler created by Visual Studio. Inc. Suppose we want to respond when our object (showButton) is clicked. To add an event handler. All Rights Reserved. 12.7).588 Graphical User Interface Concepts: Part I Chapter 12 Events icon List of events Current event handler (none) Fig. Fig. 7/5/01 . 12. Notice that Visual Studio. © Copyright 1992–2002 by Deitel & Associates. 12. Fig.8). 12.NET. It adds the event handler to the Click event using the delegate EventHandler. Visual Studio. 12.NET named the method and filled in the parameters for us (Fig. We double click the Click event.NET. This creates an empty event handler named showButton_Click. Visual Studio.NET also registers the event handler for us in method Initialize- Component (Fig. double click the name of the event to handle. Delegate EventHandler creates a new delegate object initialized with showButton_Click and adds it to the Click event.8 Event registration created by Visual Studio.NET names event handlers objectName_EventName and fills in the parameters according to the delegate.

The next step is to define the delegate.EventName. When an object needs to raise an event. then its delegate is EventNameEventHandler and the event argu- ments class is EventNameEventArgs. as well as a constructor. Visual Studio.3. In the upcoming sections we will state the EventArgs class and the EventHandler method for each event we cover. EventNameEventArgs is the class that derives from EventArgs. But how do we create a new event? First.NET can create this code for us. passing the EventArgs object and the object raising the event. 12. the components can instead listen for a event and have their update method be the event han- dler.1 As a quick review. user-defined events are useful for informing a number of components about an occurrence. To find out more information about an event. In this case a separate event arguments class is not needed and we can simply use class EventArgs (which has no fields).Chapter 12 Graphical User Interface Concepts: Part I 589 Testing and Debugging Tip 12. it will create a new EventArgs object. look in the help doc- umentation under ClassName. 12. we must create the event class. initialize it with the constructor and pass the object to the delegate. and is passed to the event handler (along with the object that raised the event). If an event uses class EventArgs. the class will look like this: class NewEventNameEventArgs : EventArgs { class definition } Remember that event argument classes generally end with EventArgs. which specifies the method signature used by the event handlers. EventNameEventArgs e ). The class definition should include the fields that the event handler will want to access. Rather than explicitly calling update methods in each component. the information we need to register an event is the EventArgs class (to define the event handler) and the EventHandler delegate (to register the event handler). The class that generates the event must define a delegate of the fol- lowing format: public delegate void EventNameEventHandler( object sender. Inc. and are always derived from EventArgs. then the del- egate is EventHandler.2 Creating New Events In the previous section we described how to register an event handler for a predefined event. However. Delegates are usually public so other objects can use them. This delegate defines the signature of the event handlers.1 Events for prepackaged components usually have a consistent naming scheme. This class derives from class EventArgs. or we can type it in. If a class uses EventArgs without deriving from it. 7/5/01 . The delegate will then call every method on its list. In general. EventNam- eEventHandler is the name of the delegate and sender is the object that raised the event. but any access modifier may be used. All Rights Reserved. If the event is named EventName. Some events do not need to convey information other than the fact that they occurred. then it should use delegate EventHandler. © Copyright 1992–2002 by Deitel & Associates.

Create event handlers with the same signature as the delegate (details in previous section). the class must define a delegate object. Create an event arguments class (EventNameEventArgs). This method is usually protected so it can be used by derived classes. An example method would be: protected void OnEventName( parameters ) { if ( EventName != null ) //check for handlers { preprocessing code // call delegate. the name of the event. Oftentimes EventName may simply be referred to as an event rather than as a delegate reference. Create an event delegate reference (EventName) in the class that raises an event. Check that the delegate reference is not null. For example.590 Graphical User Interface Concepts: Part I Chapter 12 Next. 2. the method that calls the Click delegate is named OnClick. they cannot change it in any other way. the steps for creating an event are: 1. This will then call all the event handlers. the class that raises the event must have internal code to call the EventName delegate. which calls event handlers EventName( this. Phrases such as “adding a handler to the event” may be used rather than “adding a handler to the delegate. using or derived from EventArgs. 5. The Even- tArgs object may be passed as a parameter or created inside the method. to which the delegates for event handlers are added. Create a method (OnEventName) to call the delegate when an event occurs. Add event handlers to the delegate (details in previous section). The naming convention for this method is OnEventName.” Lastly. be sure to test that the delegate reference is valid (that one or more event han- dlers have been assigned). All Rights Reserved. The delegate reference is declared with the statement: public event EventNameEventHandler EventName. © Copyright 1992–2002 by Deitel & Associates. In review. Remember that EventName. but there should be some way that other objects can call it (perhaps through an accessor method). 6. As a final caution. The delegate should not be called if no handlers have been set. 3. Define a delegate (EventNameEventHandler). } } The this keyword passes the current object as the one raising the event. Inc. is actually a EventNameEventHandler delegate reference of type event. 7/5/01 . 4. We actually declare a reference to a delegate object and do not create it ourselves (the clients create the object when they register an event handler). The method does not have to be public. Other objects can only add (+=) or subtract (-=) event handlers from the delegate ref- erence. EventArgsObject ).

we will simulate a fire department. 19 } 20 } 21 22 } // end class FireAlarmEventArgs Fig. When an event is raised. Chapter 12 Graphical User Interface Concepts: Part I 591 Prepackaged components have their delegates defined so we only have to complete the last two steps. Inc.10).3. 8 9 public FireAlarmEventArgs( string location ) 10 { 11 this. are registered with the fire department.9). 2 3 // class FireAlarmEventArgs derives from EventArgs 4 // and contains event information 5 class FireAlarmEventArgs : EventArgs 6 { 7 private string location. 12. 12. Smoke alarms.9 Class FireAlarmEventArgs Next. 12 } 13 14 public string Location 15 { 16 get 17 { 18 return location.location = location. 1 using System. Class FireAlarm- EventArgs derives from class EventArgs and contains a string (location). 12. 12. © Copyright 1992–2002 by Deitel & Associates. method OnEvent- Name should call the delegate and the event argument class should be EventNameEven- tArgs (if a new class is created). This class must define and create the event delegate and call it when the event occurs. the fire department determines the location of the event and responds. A sample alarm and re- sponce occur are displayed at the bottom of Fig. which can raise events.12. 7/5/01 . If the event is named EventName. we must create the class that raises the event (Fig.3 Event Example: A Fire Department To demonstrate a user-defined event. Class SmokeDetector contains a string (location) which is the location of the smoke detector and is set by the constructor. which is the location of the event. It is important to have a consistent naming convention. All Rights Reserved. This information can be accessed using property Location (line 14). 12. the delegate should be EventNameEventHandler. The first step is to create an event arguments class (Fig.

53 FireAlarmEventArgs e = new FireAlarmEventArgs( location ). All Rights Reserved. pass to OnFireAlarm 50 public void Alarm() 51 { 52 Console. 28 29 // define the event delegate 30 public delegate void FireAlarmEventHandler( object sender. then calls the event delegate. 40 } 41 42 // check for handlers. 55 } 56 57 } // end class SmokeAlarm Fig. © Copyright 1992–2002 by Deitel & Associates.location = location. It passes the object that raised the event (this) and the event arguments. 32 // create the event delegate reference 33 public event FireAlarmEventHandler FireAlarm. It first checks that the event reference is not null.11). 54 OnFireAlarm( e ). Line 33 declares a reference to an event delegate FireAlarm (notice keyword event). // pass this object 47 } 48 49 // create event object.WriteLine( "Smoke detector installed at " + 39 location ). e ). we create class FireDepartment to respond to the event (Fig. then call delegate 43 protected void OnFireAlarm( FireAlarmEventArgs e ) 44 { 45 if ( FireAlarm != null ) // check for handlers 46 FireAlarm( this. Method OnFireAlarm takes a FireAlarm- EventArgs object. Method OnFireAlarm is protected. it creates a new FireAlarmEventArgs object using the location of the smoke detector and calls method OnFireAlarm (line 54).WriteLine( "Smoke alarm at " + location ). Inc. 12. 31 FireAlarmEventArgs e ). Next. 38 Console. 34 35 public SmokeDetector( string location ) 36 { 37 this. Method Alarm is public and is used to raise the event. which takes an object and an EventArgs object.10 Class SmokeDetector. 12. When called. 592 Graphical User Interface Concepts: Part I Chapter 12 23 // class SmokeDetector defines the event delegate and object 24 // and calls the delegate when the event occurs 25 class SmokeDetector 26 { 27 string location. so it can be used by classes that derive from class Smoke- Detector. Line 30 defines the event delegate (FireAlarmEventHandler). 7/5/01 .

WriteLine( "Smoke detector registered " + 73 "at fire department" ). 74 } 75 76 // method signtaure matches delegate 77 void Respond( object sender. Chapter 12 Graphical User Interface Concepts: Part I 593 58 // class FireDepartment registers an event handler and 59 // responds when the event occurs 60 class FireDepartment 61 { 62 SmokeDetector smokeDetector. set in the constructor (line 66). 81 } 82 83 } // end class FireDepartment Fig. we are on our way!" ). class EventExample (Fig. Inc. FireAlarmEventArgs e ) 78 { 79 Console. 7/5/01 .11 Class FireDepartment. which drives the program. 67 68 // register event handler 69 smokeDetector.FireAlarm += 70 new SmokeDetector. It then registers its method Respond with event FireAlarm. 12.12) contains method Main." ). 63 64 public FireDepartment( SmokeDetector smokeDetector ) 65 { 66 this. All Rights Reserved. 96 Fig.12 Class EventExample. as required. © Copyright 1992–2002 by Deitel & Associates. Lastly.Location + ". Class FireDepartment has a reference to a SmokeDetector object. 92 93 // add to fire department 94 FireDepartment fireDepartment = 95 new FireDepartment( smokeDetector ). 12. 84 // driver program for the example 85 class EventExample 86 { 87 static void Main( string[] args ) 88 { 89 // create new smoke detector 90 SmokeDetector smokeDetector = 91 new SmokeDetector( "102 East Main St. 71 72 Console.FireAlarmEventHandler( Respond ).WriteLine("Fire department responding to alarm at " 80 + e.smokeDetector = smokeDetector. 12. It uses the Location property of class FireAlarmEventArgs to print where the alarm occurred. Method Respond (line 77) has the same signature as the FireAlarmEventHandler delegate.

594 Graphical User Interface Concepts: Part I Chapter 12 97 smokeDetector. Figure 12. 12. BorderStyle Border of control (none. Smoke detector registered at fire department Smoke alarm at 102 East Main St. Buttons and TextBoxes Labels provide text instructions or information on a GUI. Font Font used by the text on the control. which raises event FireAlarm and is handled by method Respond. event argument class Click EventHandler. Fire department responding to alarm at 102 East Main St. 12. center or right) and one of three vertical positions (top. derived from class Control (namespace System.Forms). middle or bottom). // raise event 98 Console. Default when component dou- ble-clicked in designer. Image Image to display on the control. 7/5/01 . we are on our way! Fig. single or 3D border). Choose one of three horizontal posi- tions (left.”) and passes this to a new fire department object.. Labels are defined with class La- bel. Occurs when user clicks the control. Once labels are created.12 Class EventExample. © Copyright 1992–2002 by Deitel & Associates.4 Labels. All Rights Reserved. Inc.13 Label properties and events. TextAlign Alignment of text on control. Label Events and Properties Description / Delegate and Event Arguments Common Properties BackColor Background color of control. Text Text to appear on the control. EventArgs. Fig. but rather to display text. 12.Windows. 99 } 100 101 } // end EventExample RunExample Smoke detector installed at 102 East Main St. programs rarely change its contents. It then calls SmokeDetector method Alarm.Alarm(). Common Events Labels are not usually used with events. Event delegate.13 lists common properties and events of Labels.ReadLine(). A Label displays read-only text. Method Main creates a smoke detector (at location “102 East Main St.

textbox can span multiple lines. Font Font used by the text on the control.Chapter 12 Graphical User Interface Concepts: Part I 595 Good Programming Practice 12. Both types of text boxes are common when logging on to a computer or Web site. textbox cannot be changed and has a grey (not white) background. We will learn how to respond to key presses in Section 12.14 lists the common properties and events of TextBoxes. The username textbox usually displays the name typed in while the password text box only displays asterisks (*) when the password is typed. hori- zontal. 12. BackColor Background color of control. Fig. Default false. PasswordChar Single character to display instead of typed text. pressing Enter clicks the default button of the form. A password textbox is a type of TextBox that only displays a certain character as the user types.10.31). Occurs when text changes in TextBox. Figure 12. making the Text- Box a password box. EventArgs.14 TextBox properties and events. 12. Default true. vertical or both). center or right) and one of three vertical positions (top. Mouse events See mouse event table (Fig. This assumes the text input was a password and should not be displayed. Text Text to appear on the control.29). TextBox events and properties Description / Delegate and Event Arguments Common Properties AcceptsReturn If true. middle or bottom). indicates what scrollbars appear (none. Choose one of three horizontal posi- tions (left.2 A TextBox is a single-line area in which text can be entered by the user from the key- board or text can simply be displayed. ScrollBars For multiline textboxes. Enabled If false. Common Events Event delegate. 12. single or 3D border). Key events See key event table (Fig. 7/5/01 . Inc. 12. Default is no character. © Copyright 1992–2002 by Deitel & Associates. Default true. pressing Enter makes a new line in a multiline textbox. All Rights Reserved. BorderStyle Border of control (none. If false. TextAlign Alignment of text on control. Multiline If true. Default when component double-clicked in designer.2 Study the methods of class Label in the documentation to learn the complete capabilities of the class before using it. event argument class TextChanged EventHandler.

A GUI can have many Buttons.Forms). Use a labeled Button (i. 12. All Rights Reserved. and the text appears on the Label. Fig. center or right) and one of three vertical positions (top. The user enters text into a password box (a type of TextBox). Common Events Event delegate. Occurs when user clicks the control. Choose one of three horizontal posi- tions (left. TextBoxes and other controls can respond to user clicks. Pressing the Enter Key Set the AcceptButton property of the form to a button. Pressing the Escape Key Set the CancelButton property of the form to a button. Inc.Windows. Good Programming Practice 12. often used to initiate a command. The following discussion explains how we created the program. Figure 12. © Copyright 1992–2002 by Deitel & Associates. Default when component dou- ble-clicked in designer. The text on the face of a Button is called a button label. single or 3D border). TextAlign Alignment of text on control. presses the Button. but each button label should typically be unique. Text Text to appear on the control.15 Button properties and events. OK) to initiate a user action. Button events and properties Description / Delegate and Event Arguments Common Properties BackColor Background color of control. The button will be clicked when the Enter key is pressed.29). such as checkboxes and radio buttons. 12. The button will be clicked when the Enter key is pressed. We learned how to create GUIs in Chapter 2.15 lists the common properties and events of But- tons. 12. 12. Mouse events See mouse event table (Fig. A C# program can use several other types of buttons.3 Although Labels. Font Font used by the text on the control. BackgroundImage Background image for the control. 7/5/01 . EventArgs. and now we will learn how to add functionality. we concentrate on the class Button. The program in Fig. middle or bottom).3 The other button types are covered in the upcoming sections. event argument class Click EventHandler. which defines many common features of buttons. rather than another type of control. All the button types are derived from ButtonBase (namespace System. Buttons naturally convey this meaning. a Button and a Label.e.16 uses a TextBox. In this section. BorderStyle Border of control (none.596 Graphical User Interface Concepts: Part I Chapter 12 A button is a component the user clicks to trigger a specific action.

Data.ComponentModel. 7/5/01 .cs 2 // Using a textbox.Container components = null. TextBox and Button 20 private System. 11 12 namespace LabelTextBoxButtonTest 13 { 14 /// <summary> 15 /// Summary description for LabelTextBoxButtonTest.Windows.Windows.Windows. Chapter 12 Graphical User Interface Concepts: Part I 597 1 // LabelTextBoxButtonTest. 34 35 // 36 // TODO: Add any constructor code after 37 // InitializeComponent call 38 // 39 } 40 41 /// <summary> 42 /// Clean up any resources being used. 7 using System. 25 /// </summary> 26 private System. 12.16 Program to display hidden text in a password box.Form 18 { 19 // declare the Label.ComponentModel. 16 /// </summary> 17 public class LabelTextBoxButtonTest : System. Inc. 10 using System.Label displayLabel. 43 /// </summary> 44 protected override void Dispose( bool disposing ) 45 { 46 if( disposing ) 47 { 48 if (components != null) 49 { 50 components.Forms.Collections. 9 using System. 21 private System. 4 5 using System.Forms. © Copyright 1992–2002 by Deitel & Associates.Forms.Forms. 51 } Fig.Windows.Drawing. 8 using System. 27 28 public LabelTextBoxButtonTest() 29 { 30 // 31 // Required for Windows Form Designer support 32 // 33 InitializeComponent(). 6 using System.Button showButton. 23 /// <summary> 24 /// Required designer variable. label and button to display the hidden text 3 // in a password box.Windows.Dispose().TextBox inputTextBox. All Rights Reserved. 22 private System.Forms.

Drawing. 89 // 90 // showButton 91 // 92 this.Location = new System. 16 ). 74 this. 72 this.Drawing.Label().Size( 86 264.Windows.Size( 5.Text = "".ClientSize = new System.BorderStyle.showButton. 13 ). © Copyright 1992–2002 by Deitel & Associates.Name = "inputTextBox".BorderStyle = 71 System.Text = "Show Me". 104 this.displayLabel.displayLabel.displayLabel = new System. 75 this.PasswordChar = '*'.Drawing.AutoScaleBaseSize = new System. 96 this.showButton. 88 this. 20 ). 23 ).inputTextBox. 97 this.Drawing.showButton. 103 this.inputTextBox. Fig. 95 this.inputTextBox.inputTextBox.EventHandler( 98 this.Dispose( disposing ). 67 // 68 // displayLabel 69 // 70 this.Click += new System. 83 this. 598 Graphical User Interface Concepts: Part I Chapter 12 52 } 53 base.Drawing. 65 this. 84 this.inputTextBox.Control[]{ this. 54 } 55 56 #region Windows Form Designer generated code 57 /// <summary> 58 /// Required method for Designer support .Controls.Size = new System.Point( 82 16.showButton.do not modify 59 /// the contents of this method with the code editor. 7/5/01 . 78 // 79 // inputTextBox 80 // 81 this. 77 this. 60 /// </summary> 61 private void InitializeComponent() 62 { 63 this.Windows. Inc.TabIndex = 0. 48 ). 94 this.showButton = new System.Windows.Forms.displayLabel.Forms.TextBox(). 66 this.Forms.Windows.AddRange( 105 new System. 12. 96 ).Location = new System.Drawing.Location = new System.Button().Windows.inputTextBox = new System.Name = "showButton".displayLabel.Size = new System.Drawing.Forms.inputTextBox.SuspendLayout().Fixed3D.Size( 76 264.Forms.Point( 73 16. 85 this.displayLabel. All Rights Reserved.16 Program to display hidden text in a password box.Name = "displayLabel".showButton_Click ).TabIndex = 2. 99 // 100 // LabelTextBoxButtonTest 101 // 102 this.showButton.Size( 292.displayLabel. 64 this. 87 this.Point( 93 96. 133 ).TabIndex = 1.

we created the GUI by dragging the components (a Button.Text = "LabelTextBoxButtonTest". The PasswordChar property can take exactly one character—the character to display in place of the input. Chapter 12 Graphical User Interface Concepts: Part I 599 106 this.Text. inputTextBox and showButton.Name = "LabelTextBoxButtonTest". First. 116 /// </summary> 117 [STAThread] 118 static void Main() 119 { 120 Application. Text box inputTextBox is still a regular TextBox and does not hide its input char- acters. 12.showButton } ). The code to make our property changes was created by Visual Studio. Inc. Note that all of these changes were done inside the Properties window and no coding was needed. 107 this.ResumeLayout( false ).16 Program to display hidden text in a password box.NET © Copyright 1992–2002 by Deitel & Associates. 109 this. 110 111 } 112 #endregion 113 114 /// <summary> 115 /// The main entry point for the application. 128 } 129 130 } // end class LabelTextBoxButtonTest 131 } Fig. Label and TextBox) onto the form. All Rights Reserved.inputTextBox. 7/5/01 . 125 System. button1) to the more descrip- tive displayLabel. 121 } 122 123 // display user input on label 124 protected void showButton_Click( object sender.Run( new LabelTextBoxButtonTest() ). Once positioned. this. We then set displayLabel’s Text property to “Show Me” and cleared the Text of displayLabel and inputTextBox so they are initially blank when the program runs.Text = inputTextBox.EventArgs e ) 126 { 127 displayLabel. To make it a password box we set the PasswordChar property to an asterisk (*). we changed their names (by setting the Name property) from the default values (textBox1. label1. 108 this.

Lines 83–86 change the Name. All Rights Reserved.NET generated comments and method Dispose. Inc. © Copyright 1992–2002 by Deitel & Associates.NET its name appears instead of an ellipsis. Next comes the class definition (line 17)—Visual Studio. To show the text we set dis- playLabel’s Text to inputTextBox’s Text on line 119. This simplifies the example program and allows us to focus on the program logic. which points to any components we add. especially for programs with many controls. which names a region. Given all the generated code. PasswordChar and Text properties.NET and determines the order the components are cycled through by pressing the Tab key. while others can be determined by exam- ining the program output. The entire code for every example can be found on our Web site (www. Visual Studio.3. This is discussed in Chapter 13. let us examine the code that Visual Studio. which will be discussed in Chapter 26. which is by default the name of the project. Line 109 declare attribute [STATh- read]. The Click event fires when a control is clicked. 7/5/01 .600 Graphical User Interface Concepts: Part I Chapter 12 inside method InitializeComponent. The TabIndex property is set by Visual Studio. In this chapter we will show the important code that Visual Studio. In future examples.1. we will not include the namespace. This creates an empty event handler named showButton_Click (line 124).NET generates. Line 56 contains a #region tag followed by a title. Visual Studio. Lines 5–10 state our namespaces. we only need to write the Click event handler for showButton. such as such as setting the PasswordChar on line 84. XML tags and comments help to create documentation and are indicated by a triple slash (///). Lines 63–65 create new objects for the controls we added (a Button. Even though inputTextBox displays all asterisks. it still retains its input text in its Text property. When the region is collapsed in Visual Studio. replacing it with a comment such as “Visual Studio. Lines 118–121 define method Main.NET creates object declara- tions for the components we add (lines 19–21). We create the handler using the procedure described in Section 12. and are preceded by a comment with the object’s name. Phew! Visual Studio. Examples of these comments can be seen on lines 14– 16. It adds the event handler to the Click event using the EventHandler delegate. We then implement the event handler. However. Whenever showButton is clicked we display inputTextBox’s text on displayLabel. a Label and a TextBox). Method InitializeComponent (line 61) contains the details of each component. The code appears in Fig. Lines 67–108 set the properties for the controls and the form.NET generated a lot of code for us.” We will simply state which properties to set for each component. It would be cumbersome and confusing to display all this code. The constructor (line 28) calls method Initial- izeComponent and has some generated comments. Method Dispose (line 44) is cre- ated. Each #region tag is accompanied by an #endregion tag (line 112). A new namespace is created for us (line 12).NET generated code.NET also registers the event handler for us (line 97). Lines 66 and 109 call layout methods that we will not cover.com).deitel.NET has generated. Before we go further. 12. we are not using any components (only controls) and thus the reference is null. When showButton is clicked the Click event raises and the event handler showButton_Click runs (updating displayLabel).16. so we double click it in the Events window. We want to respond to the Click event showButton. We will also hide the details of method InitializeComponent. which cleans up memory for any components we add. Line 26 declares reference components.

Chapter 12 Graphical User Interface Concepts: Part I 601 Visual Studio. Text Text to appear on the control. Common Events GroupBoxes are usually not used with events. To create a GroupBox. 12.NET form designer. 12. and they will all move together when the group box or panel is moved. Panels and GroupBoxes can contain other Panels and GroupBoxes. Occurs when mouse enters control. create new components and place them inside the GroupBox. Fig. EventArgs. Controls Gets or sets a collection of controls that the GroupBox contains. Event delegate. All Rights Reserved. 12.5 GroupBoxes and Panels GroupBoxes and Panels help to arrange components on a GUI. We only had to create one line of code (excluding comments) in a program of over 100 lines! This is a great example of the productivity of visual programming. Default when component double- clicked in designer.com). and the properties that are not clear will be stated. Inc. event argument class Enter EventHandler.18). in future examples we will simplify things by not showing the details of Ini- tializeComponent unless there is an important new property being set.deitel. GroupBox events and properties Description / Delegate and Event Arguments Common Properties BackColor Background color of control. BackgroundImage Background image for the control.NET generates the rest of the code so we have finished programming. The following tables list the common properties and events of GroupBoxes (Fig. 12. The main difference between the two is that GroupBoxes can display text and Panels can have scrollbars. In addition. drag it from the toolbar and place it on a form. The user will see many control properties from the screen captures and functionality of the program. Font Font used by the text on the control. Similar buttons can be placed inside a group box or panel inside the Visual Studio.17 GroupBox properties and events.17) and Panels (Fig. but Panels can be set to have a border (set their BorderStyle property). 7/5/01 . Again. but rather to organize controls. © Copyright 1992–2002 by Deitel & Associates. Then. The GroupBox’s Text property determines its caption. The entire code for the example programs can be found on our Web site (www. GroupBoxes have a thin border by default. and they will become part of it.

event argument class Enter PaintEventHandler. drag it onto the form and add components to it. © Copyright 1992–2002 by Deitel & Associates. BackColor Background color of control. Default when component double-clicked in designer. Fig. but rather to organize con- trols. Event delegate. BackgroundImage Background image for the control. enlarge the Panel and space out its components. To create a Panel. If the size of the panel decreases. These scrollbars can then be used to see all the components in the Panel (when both running and designing). Occurs when control needs to be repainted. To use its scroll- bars. BorderStyle Border of control (none.602 Graphical User Interface Concepts: Part I Chapter 12 Panel events and properties Description / Delegate and Event Arguments Common Properties AutoScroll If true. set its AutoScroll property to true. Controls Gets or sets a collection of controls that the Panel contains.19). Text Text to appear on the control.18 Panel properties and events. allows the user to scroll to see controls outside the visible region. Common Events Panels are usually not used with events. scrollbars appear (Fig. single or 3D border). PaintEventArgs. 7/5/01 . Default false. All Rights Reserved. Inc. 12. 12. Font Font used by the text on the control. To take advantage of this.

20 Using GroupBoxes and Panels to arrange Buttons.Label messageLabel.Forms. 21 22 public GroupBoxPanelExample() 23 { 24 InitializeComponent(). 12.Container components = null. 3 4 using System.Forms. © Copyright 1992–2002 by Deitel & Associates.Forms.Button leftButton.Drawing. All Rights Reserved. 9 using System.Button byeButton.Data.Windows.GroupBox mainGroupBox.Forms.Windows. 16 private System.19 Creating a Panel with scrollbars.Windows.Button rightButton.Forms.Forms. 19 private System.ComponentModel. 7/5/01 .Collections. 6 using System. 15 private System. 25 } Fig. 10 11 public class GroupBoxPanelExample : System. 5 using System.Windows.Windows.cs 2 // Using GroupBoxes and Panels to hold buttons.Windows.Windows. which change the text on a Label.Windows. Inc.ComponentModel.20 demonstrates how to use a GroupBox and a Panel to arrange buttons. 8 using System. 17 private System. 1 // GroupBoxPanelExample. The program of Fig. Chapter 12 Graphical User Interface Concepts: Part I 603 Panel components Panel Panel Scrollbars Fig. 14 private System. 18 private System.Forms.Windows.Panel mainPanel.Forms. 12.Forms.Button hiButton. 12. 20 private System. 7 using System.Form 12 { 13 private System.

Control[] { this.AddRange( 37 new System. // far left button 69 } 70 71 private void rightButton_Click( object sender. 50 } 51 52 // event handlers to change messageLabel 53 private void hiButton_Click( object sender. Inc.Text = "Far left pressed". 38 this. 66 System.Windows.Click += new System.EventHandler( 33 this.Control[] { this.EventArgs e ) 55 { 56 messageLabel. 43 this.EventArgs e ) 73 { 74 messageLabel.Controls. 39 40 // add controls to mainPanel 41 this.byeButton. All Rights Reserved.Controls. 7/5/01 . 44 } 45 46 [STAThread] 47 static void Main() 48 { 49 Application. // far right button 75 } 76 77 } // end class GroupBoxPanelExample Fig.Text= "Hi pressed".leftButton } ).mainPanel.Forms.Forms. 72 System.Windows.EventArgs e ) 67 { 68 messageLabel. // bye button pressed 63 } 64 65 private void leftButton_Click( object sender.20 Using GroupBoxes and Panels to arrange Buttons.Text = "Far right pressed".AddRange( 42 new System.hiButton } ).mainGroupBox. 34 35 // add controls to mainGroupBox 36 this. © Copyright 1992–2002 by Deitel & Associates.byeButton_Click ).byeButton.Text = "Bye pressed".NET generated code 30 31 // register event handler 32 this. // hi button pressed 57 } 58 59 private void byeButton_Click( object sender. 60 System.Run( new GroupBoxPanelExample() ). 54 System. 604 Graphical User Interface Concepts: Part I Chapter 12 26 27 private void InitializeComponent() 28 { 29 // Visual Studio.EventArgs e ) 61 { 62 messageLabel.rightButton. 12.

NET. some or none of them may be selected. Any. When the checkbox is selected the checkmark appears. The mainPanel component also has its AutoScroll property set to True. 12. to add components to mainPanel.Add can be used to add a single component. leftButton (labeled Far Left) and rightButton (labeled Far Right). allowing scrollbars to appear.6 CheckBoxes and RadioButtons Visual C# has two types of state buttons— CheckBox and RadioButton—that can be in the on/off or true/false state.Control array con- taining the components (line 37). The text that appears © Copyright 1992–2002 by Deitel & Associates. The GroupBox (named mainGroupBox) has two buttons. which can either be blank or have a black checkmark (there is also an indeterminate checkmark which is not discussed here). To create an empty Click event handler. Visual Studio creates a Windows. We added a line in each handler to change the text of messageLabel.20 Using GroupBoxes and Panels to arrange Buttons. hiButton (labeled Hi) and byeButton (labeled Bye). It then passes the array to method AddRange. The Label (named messageLabel) is originally blank. Similarly.AddRange method (line 41). double click the button in design mode (instead of using the Events window). Method Controls. Let us look at the relevant code generated by Visual Studio.Control array and passes it to the main- Panel’s Controls. 12. of the Controls collection in the GroupBox. 7/5/01 . A RadioButton is different from a CheckBox in that there are normal- ly several RadioButtons that are grouped together and only one of the RadioButtons in the group can be selected (true) at any time. We first discuss class CheckBox. The Panel (named mainPanel) has two buttons as well. Chapter 12 Graphical User Interface Concepts: Part I 605 Fig. Visual Studio created a Windows.Forms. Inc. A checkbox is typically a small white square. All Rights Reserved. and there is no logical restriction on groups of checkboxes.Forms. Classes CheckBox and RadioButton are derived from ButtonBase. To add components to mainGroupBox. The event handlers for the four buttons are found on lines 52–75.

unchecked or indeterminate (light grey check mark). CheckBox events and properties Description / Delegate and Event Arguments Common Properties BackColor Background color of control.Forms. Occurs when the Checked property changes.22 Using CheckBoxes to change font styles. EventArgs. CheckState Sets whether the Checkbox is checked. 3 4 using System. neither CheckBox is checked (true). Inc. Changed Occurs when the CheckState property changes.ComponentModel. 606 Graphical User Interface Concepts: Part I Chapter 12 alongside a checkbox is referred to as the checkbox label. 12.Data. 12. the style of the font is bold and italic. TextAlign Alignment of text on control. All Rights Reserved. center or right) and one of three vertical positions (top. 6 using System. Common Events Event delegate.21 CheckBox properties and events.Collections.Drawing. Choose one of three horizontal posi- tions (left. Text Text to appear on the control. 12. Checked Sets or gets whether the CheckBox is checked (true). A list of common properties and events of class Checkbox appears in Fig. Occurs when user clicks the control. One CheckBox applies a bold style when selected and the other applies an italic style when selected. EventHandler. If both are selected. CheckState. EventArgs. 5 using System. Fig.Windows.Windows. CheckedChanged EventHandler. Font Font used by the text on the control.22 uses two CheckBoxes to change the font style of the text displayed in a Label. middle or bottom). When the program initially executes. 9 using System.Form 12 { Fig.21.cs 2 // Using CheckBoxes to toggle italic and bold styles. event argument class Click EventHandler. EventArgs. 1 // CheckBoxTest. 7 using System. The application of Fig. 12.Forms. © Copyright 1992–2002 by Deitel & Associates. 10 11 public class FormCheckBoxTest : System. Default when compo- nent double-clicked in designer. 7/5/01 . 8 using System.

Windows.NET generated code 26 27 // register event handlers 28 29 this. 47 outputLabel. 16 private System.Style ^ FontStyle.Label outputLabel. 49 } 50 51 // use XOR (^) to toggle italic.Size.Font.Italic ).EventArgs e ) 45 { 46 outputLabel.checkBoxItalic_CheckedChanged ). 56 outputLabel.Size.Font. 12.Windows.Font. keep other styles the same 43 private void checkBoxBold_CheckedChanged( object sender. 14 private System. keep other styles the same 52 private void checkBoxItalic_CheckedChanged( object sender. 31 32 this.Style ^ FontStyle.Forms. 15 private System. 58 } 59 60 } // end class FormCheckBoxTest Fig.EventHandler( 33 this. 17 18 public FormCheckBoxTest() 19 { 20 InitializeComponent().Font. 21 } 22 23 private void InitializeComponent() 24 { 25 // Visual Studio.boldCheckBox. 44 System.CheckedChanged += new System. 48 outputLabel. 7/5/01 .Name.CheckedChanged += new System.Forms.Forms.checkBoxBold_CheckedChanged ).EventHandler( 30 this.Run( new FormCheckBoxTest() ).Font = new Font( outputLabel. 57 outputLabel.CheckBox italicCheckBox. Inc.Name.22 Using CheckBoxes to change font styles. All Rights Reserved.EventArgs e ) 54 { 55 outputLabel.Bold ).Font. 53 System.CheckBox boldCheckBox.Font. 34 } 35 36 [STAThread] 37 static void Main() 38 { 39 Application. © Copyright 1992–2002 by Deitel & Associates.Font = new Font( outputLabel. Chapter 12 Graphical User Interface Concepts: Part I 607 13 private System.Windows.Container components = null. 40 } 41 42 // use XOR (^) to toggle bold.italicCheckBox.ComponentModel.

The CheckChanged event fires when the CheckBox changes. 7/5/01 . XOR. We could have explicitly tested for the current style. size and a style. AND. named boldCheckBox.Italic). To change the font. © Copyright 1992–2002 by Deitel & Associates. bold (FontStyle. We do not need to test whether the style is already italic or bold.Font. The style comes from FontStyle.Name and outputLabel. in the bold CheckChanged event we could have tested for the regular style. To toggle a single bit we use the bitwise exclusive OR operator (XOR). we can use XOR to toggle the bit representing italic or bold. made it regular. the Font property must be set to a Font object. which has bit flags for regular (FontStyle. Double clicking a CheckBox creates and registers its CheckedChanged event handler (lines 29 and 43). The Text property of a CheckBox what determines the label. named outputLabel. has a Text property of Bold.Bold) or italic (Fontstyle.Regular). We then examine the Font property of outputLabel. the bold style.22 Using CheckBoxes to change font styles. If our bit is 1 and we XOR it with 1. FontStyle also has Underline and Strikeout flags. namely outputLabel. Thus. indicated by the ^ symbol. The first two parameters come from out- putLabel’s Font object. 608 Graphical User Interface Concepts: Part I Chapter 12 Fig. if our bit is 0 and we XOR it with 1. so only a toggle is necessary. All Rights Reserved. The first CheckBox.Font.Size (lines 46–47). the result is 1 (exactly one bit is 1). For example. 12. the italic style. is labeled “Watch the font style change”. and changed it according to what we needed. The XOR of two bits is 1 if exactly one of the bits is 1. Inc. One Font con- structor takes the font name. A combination of flags can be made using the bitwise operators (OR. After creating the components we define their event handlers. made it bold italic. For example.). etc. The Label. the result is 0 (because both bits are one). When a bit is XORed with 1 it toggles. made it bold. The other CheckBox is named italicCheckBox and labeled Italic.

radio buttons must be added to GroupBoxes or Panels. EventArgs. This method has a drawback because for every new style we add. If we tested for every condition. All Rights Reserved. RadioButton events and properties Description / Delegate and Event Arguments Common Properties BackColor Background color of control. 12. middle or bottom). If we wanted to add a checkbox for strikeout as well. The common properties and events of class RadioButton are listed in Fig. CheckedChanged EventHandler. In addition.1 Radio buttons (defined with class RadioButton) are similar to checkboxes because they also have two states—selected and not selected (also called deselected). Text Text to appear on the control. we would have 16 tests in each event handler. EventArgs. we save ourselves from this trouble.23 RadioButton properties and events. Occurs when user clicks the control. Selecting a different radio button in the group forces all other radio buttons in the group to be deselected. Font Font used by the text on the control. we would have to test for 8 possible styles. Common Events Event delegate. Fig. Radio buttons represent a set of mutually exclusive options (i. center or right) and one of three vertical positions (top. Default when compo- nent double-clicked in designer. Thus. Choose one of three horizontal posi- tions (left. Checked Sets or gets whether the RadioButton is checked (true). Software Engineering Observation 12. Each new style only needs a single statement in its event handler. TextAlign Alignment of text on control.1 Using XOR to toggle bits allows the programmer to add and remove bitwise options easily.. multiple options in the group would not be selected at the same time).Chapter 12 Graphical User Interface Concepts: Part I 609 the italic bold style and made it italic. we would have to remove the handler as well as all the unnecessary test conditions in the other handlers. By using the bitwise XOR operator.23. Inc. However. 7/5/01 . To create new groups. styles can be removed easily: simply remove their handler.e. 12. © Copyright 1992–2002 by Deitel & Associates. radio buttons normally appear as a group in which only one radio button can be selected at a time. All radio buttons added to the form become part of the same group. event argument class Click EventHandler. 12. Each GroupBox or Panel is its own group. Occurs when the Checked property changes. we double the number of combinations. to add a checkbox for under- line.

A Label in the lower left corner shows the result of the mes- sage box (yes.Windows. 1 // RadioButtonTest. 31 private System. 25 private System.Windows. 7 using System.Windows.RadioButton stopButton.Drawing. 22 private System.RadioButton exclamationButton. 17 private System. 26 private System.Windows.RadioButton questionButton.Forms. 24 private System.RadioButton yesNoButton.Forms. All Rights Reserved.Forms.Forms. no. etc.RadioButton okCancelButton. 10 11 public class RadioButtonsTest : System.Button displayButton.Windows.RadioButton informationButton. © Copyright 1992–2002 by Deitel & Associates.Collections.Forms.Windows.Forms.Forms. 3 4 using System.RadioButton errorButton. 12.).RadioButton retryCancelButton. 8 using System.GroupBox groupBox2.Forms. 18 private System.Windows. 19 private System.Windows.Forms.Container components = null.Windows. 6 using System.Windows. 20 private System.Forms. 39 } 40 41 private void InitializeComponent() 42 { 43 // Visual Studio.RadioButton warningButton.RadioButton yesNoCancelButton. The user selects the attributes he or she wants. Inc.24 uses radio buttons to select the options for a message box.GroupBox groupBox1.24 Using RadioButtons to set message window options.RadioButton asteriskButton. then presses the display button which causes the message box to appear.Asterisk.ComponentModel.Forms. 15 private System.Windows.Windows.NET generated code 44 45 // all radio buttons registered to 46 // radioButtons_CheckChanged event handler 47 this.Windows.Windows. 21 private System. 12. 9 using System.cs 2 // Using RadioButtons to set message window options.Forms.Forms. 28 private System. 33 private MessageBoxButtons buttonType = MessageBoxButtons.Forms.CheckedChanged += Fig. 29 private System.RadioButton 27 abortRetryIgnoreButton.Forms. 5 using System. 23 private System.informationButton.Windows. 35 36 public RadioButtonsTest() 37 { 38 InitializeComponent().OK. 30 private System.Form 12 { 13 private System.Forms.Windows.Windows.RadioButton okButton.Windows. 32 private MessageBoxIcon iconType = MessageBoxIcon. 7/5/01 .RadioButton handButton. 16 private System.Forms.ComponentModel.Label displayLabel.Forms. 610 Graphical User Interface Concepts: Part I Chapter 12 The program of Fig.Data. 14 private System.Forms.Windows.Windows. 34 private System. cancel.Forms.

12. 65 else if ( sender == okCancelButton ) 66 buttonType = MessageBoxButtons. change appropriate setting 59 protected void radioButtons_CheckedChanged( object sender.Run( new RadioButtonsTest() ). Chapter 12 Graphical User Interface Concepts: Part I 611 48 new System.YesNo.Warning.24 Using RadioButtons to set message window options.Hand. 60 EventArgs e ) 61 { 62 // test for changes in buttons or icons 63 if ( sender == okButton ) // change in button 64 buttonType = MessageBoxButtons.Stop. 87 else if ( sender == stopButton ) 88 iconType = MessageBoxIcon. 75 else if ( sender == asteriskButton ) // change in icon 76 iconType = MessageBoxIcon. 56 } 57 58 // find which radio button changed. 85 else if ( sender == questionButton ) 86 iconType = MessageBoxIcon.Exclamation. 91 } 92 93 // display MessageBox and button user pressed 94 protected void displayButton_Click( object sender. 79 else if ( sender == exclamationButton ) 80 iconType = MessageBoxIcon.Show( "C# How To Program". iconType.Asterisk. 67 else if ( sender == abortRetryIgnoreButton ) 68 buttonType = MessageBoxButtons.RetryCancel. 81 else if ( sender == handButton ) 82 iconType = MessageBoxIcon. 69 else if ( sender == yesNoCancelButton ) 70 buttonType = MessageBoxButtons. 7/5/01 . 95 System. All Rights Reserved.EventHandler( 49 this. 89 else if ( sender == warningButton ) 90 iconType = MessageBoxIcon.radioButtons_CheckedChanged ).OKCancel. 50 } 51 52 [STAThread] 53 static void Main() 54 { 55 Application. 73 else if ( sender == retryCancelButton ) 74 buttonType = MessageBoxButtons. 0. 77 else if ( sender == errorButton ) 78 iconType = MessageBoxIcon. 98 "C# HTP". 99 100 // check for the dialog result and display it on label 101 switch ( r ) Fig.Question.Error. 71 else if ( sender == yesNoButton ) 72 buttonType = MessageBoxButtons.Information. 83 else if ( sender == informationButton ) 84 iconType = MessageBoxIcon. Inc. © Copyright 1992–2002 by Deitel & Associates. 0 ). buttonType.EventArgs e ) 96 { 97 DialogResult r = MessageBox.OK.AbortRetryIgnore.YesNoCancel.

".".Cancel: 107 displayLabel. 124 } 125 } 126 127 } // end class RadioButtonsTest Fig. 117 break. 118 case DialogResult.Text = "Ignore was pressed. 114 break. 105 break. All Rights Reserved. 120 break. 123 break.".Text = "No was pressed.". 111 break. 112 case DialogResult.".Text = "OK was pressed.Text = "Yes was pressed. 106 case DialogResult.Abort: 110 displayLabel. 108 break. 12. 109 case DialogResult.Text = "Abort was pressed.Retry: 113 displayLabel.Text = "Retry was pressed.Yes: 119 displayLabel. 121 case DialogResult.Text = "Cancel was pressed.No: 122 displayLabel. 612 Graphical User Interface Concepts: Part I Chapter 12 102 { 103 case DialogResult.OK: 104 displayLabel.".24 Using RadioButtons to set message window options. 115 case DialogResult.".Ignore: 116 displayLabel. Inc. 7/5/01 . © Copyright 1992–2002 by Deitel & Associates.

RetryCancel. OKCancel. YesNo. To keep track of the user’s choice of options. Inc. “Alignment” and “Icon. Error.” The Label is named displayLabel (ini- tialized with no text) and the Button is named displayButton (with text “Dis- play”). and Warning. Each radio button generates a CheckedChanged event when clicked (line 47 shows a sample © Copyright 1992–2002 by Deitel & Associates. All Rights Reserved. The name indicates the options given to the user. OK. For event handling. Because the radio buttons are grouped. which can have values Asterisk. Stop. Hand. Chapter 12 Graphical User Interface Concepts: Part I 613 Fig. one giant event handler is made for all the radio buttons. one for each enumeration. Object buttonType is a MessageBoxButton enumeration with values Abor- tRetryIgnore. Three GroupBoxes are created. Information. Exclamation. RadioButtons were created for the enumeration options. 7/5/01 . only one option can be selected from each GroupBox. Their captions are “Button Type”. 12.24 Using RadioButtons to set message window options. the objects iconType and button- Type are created and initialized (lines 32–33). Object iconType is a MessageBox- Icon enumeration. with their labels being set appropriately. Question. YesNoCancel.

with values Abort. either iconType or buttonType changes (lines 63–90). Inc. If there are no handlers. Some of the message box options are set by iconType and buttonType. EventArgs. HScrollBar and VScrollBar events and properties Description / Delegate Event Arguments Common Properties LargeChange Amount scrollbar changes when scrollbar clicked or Page Up/Page Down keys pressed. Occurs when user changes position of scrollbar. namely horizontal HScrollBars and vertical VScrollBars. Default 0. The Click handler for displayButton creates a message box (line 97). All Rights Reserved. Then point all the other radio buttons to method radioButtons_CheckedChanged. Depending on the radio button pressed. Minimum Minimum value scrollbar can have. such as small or large change) Fig. Ignore.Text appropriately. Occurs when user clicks the control. Default 10. For each radio button. Remember. the handler was set to method radioButtons_CheckedChanged. C# proves two types of scrollbar controls. 12. create a new one and rename it radioButtons_CheckedChanged. The common properties and events of scrollbars are listed in Fig. Maximum Maximum value scrollbar can have. No.25 HScrollBar and VScrollBar properties and events. The switch statement on line 101 tests for the result and sets displayLabel. The handler compares the sender object with every radio button to determine which was pressed. We have seen scrollbars as parts of components (such as Panels) but now we will use them as separate components. Common Events Event delegate. Default 100. use the events section of the Properties window. SmallChange Amount scrollbar changes when arrow clicked. to set the event handler for an event. Scroll ScrollEventHandler.614 Graphical User Interface Concepts: Part I Chapter 12 event handler registration). OK. 12. ScrollEventArgs. Retry or Yes. Default when com- ponent double-clicked in designer. 7/5/01 . Default 1 Value Current position of scrollbar. © Copyright 1992–2002 by Deitel & Associates.7 Scrollbars Scrollbars are intrinsic controls that allow the user to access a range of integer values. None. event argument class Click EventHandler. Cancel. The result of the mes- sage box is a DialogResult enumeration. ScrollEventArgs NewValue (new value of scrollbar) Properties Type (type of scroll.25. 12.

10 11 public class UsingScrollBars : System.horizontalScrollBar.Maximum = 320. 8 using System.ScrollEventHandler( 48 this. 22 private Pen p. scrolly = 0.Windows.26.Black ).horizontalScrollBar.NET generated code 38 39 // set maximums and register event handlers 40 this.Data.HScrollBar horizontalScrollBar.ComponentModel.verticalScrollBar.Forms.Form 12 { 13 private System. 7 using System.Forms. 1 // UsingScrollBars.ScrollEventHandler( 43 this. 41 this. 19 20 // used to draw 21 private Graphics g.horizontalScrollBar_Scroll ). 23 24 private System.Windows.Collections.Forms. 14 private System. All Rights Reserved.Forms. 16 17 // current x and y locations 18 private int scrollx = 0. 29 30 // create new graphics and pen objects 31 g = canvas.Forms. Chapter 12 Graphical User Interface Concepts: Part I 615 The program in Fig.Panel canvas. 12.Scroll += 42 new System.Forms. 15 private System. 3 4 using System.Windows. 32 p = new Pen( Color.verticalScrollBar_Scroll ). 25 26 public UsingScrollBars() 27 { 28 InitializeComponent().Maximum = 320. 7/5/01 .Drawing.Windows. 33 } 34 35 private void InitializeComponent() 36 { 37 // Visual Studio.Windows. 49 } Fig. 44 45 this.Forms. Inc. 5 using System. © Copyright 1992–2002 by Deitel & Associates. 46 this.Windows. uses a HScrollBar and a VScrollBar to draw on a Panel using horizontal and vertical lines. 12.Scroll += 47 new System. 6 using System.26 Using scrollbars to draw lines on the form.cs 2 // Using Scrollbars to draw lines on the form.verticalScrollBar.CreateGraphics().ComponentModel.Windows. Moving either scrollbar moves a “pen” across the form.Container components = null.VScrollBar verticalScrollBar. 9 using System.

NewValue. scrolly) and update location 69 protected void horizontalScrollBar_Scroll( object sender. 55 } 56 57 // draw vertical line from current point (scrollx. scrolly) 68 // to new point (new x value.Windows.DrawLine( p. 70 System.NewValue. All Rights Reserved. 616 Graphical User Interface Concepts: Part I Chapter 12 50 51 [STAThread] 52 static void Main() 53 { 54 Application. © Copyright 1992–2002 by Deitel & Associates. Inc. 60 System. e. // update x coordinate 75 } 76 77 } // end class UsingScrollBars Fig.NewValue is new y coordinate 63 g. scrolly ).Run( new UsingScrollBars() ). 74 scrollx = e. scrollx. // update y coordinate 65 } 66 67 // draw horizontal line from current point (scrollx. 12.Forms. scrollx. 64 scrolly = e. scrolly) 58 // to new point (scrollx. e.DrawLine( p. 7/5/01 .Forms.ScrollEventArgs e ) 61 { 62 // e.NewValue. scrolly. scrolly.Windows.NewValue is new x coordinate 73 g. new y value) and update location 59 protected void verticalScrollBar_Scroll( object sender.NewValue ).ScrollEventArgs e ) 71 { 72 // e.26 Using scrollbars to draw lines on the form. scrollx.

it draws a line from point (x1. in this case Color. and we create event handlers on lines 59 and 69. Because the graphics object came from canvas. In C#. 12. Thus. their Maximum and Minimum (default 0) properties are set to canvas’ dimensions. The Graphics and Pen classes are discussed in more detail in Chapter 16. which is the new value of the scrollbar. We must also create a Pen object to draw on the graphics object. and y2. Thus.Black (line 32). Graphics and Multimedia. The ScrollEventArgs object e has property NewValue. we only draw on a 320 by 320 pixel area. To draw on the Panel (named canvas) we need a Graphics object (g).26 Using scrollbars to draw lines on the form. We also create two integers (scrollx and scrolly) to keep track of our current x- and y-coordinates (line 18). Chapter 12 Graphical User Interface Concepts: Part I 617 Fig. we draw a line from the old point (scrollx. 7/5/01 . x2. Using this new value. y1. For the vertical scrollbar. e. The two scrollbars (an HScrollBar and a VScrollBar) that we used to draw need to have their maximum and minimum values so they can only draw on canvas. 320 by 320 pixels in this case (lines 40 and 45)—examine the canvas’ size using its Height and Width properties in the Properties window. Inc. y1) to point (x2. After drawing the line we update the current y coordi- © Copyright 1992–2002 by Deitel & Associates. pixels are on an x-y plane. The Pen constructor is passed a color. We create g by calling method Cre- ateGraphics on line 31.NewValue) on line 63. Given a Pen. x1. scrolly) to the new point (scrollx. with the origin at the upper left corner of the control. To do this we call method drawLine on lines 63 and 73. y2) using the Pen object. This object has methods for drawing the lines we need. All Rights Reserved. We keep the same x-coordinate when moving the vertical scrollbar. both the horizontal and vertical scroll- bars go from zero to 320. we draw a line from our old point to the new one. Whenever the scrollbars are changed they raise a Scroll event.

8 using System. set by an ob- ject of class Image.27 describes the important properties and events of class Picture- Box. Whenever the imagePictureBox is clicked the image changes. Fig.Collections. Image Image to display on the control. AutoSize. Default when component dou- ble-clicked in designer. 12.8 PictureBoxes A picture box (class PictureBox) is used to display an image. 3 4 using System. 7/5/01 . 6 using System. in the same directory as the executable. . There is a Label (named promptLabel) on the top of the form with the instructions “Click On Picture Box to View Images. Inc.” 1 // PictureBoxTest. CenterImage).Data. 9 using System.27 PictureBox properties and events.28 Using a PictureBox to display images. 12.cs 2 // Using a PictureBox to display images. © Copyright 1992–2002 by Deitel & Associates. 7 using System. Occurs when user clicks the control. Figure 12. 618 Graphical User Interface Concepts: Part I Chapter 12 nate (line 64). . PictureBox events and properties Description / Delegate and Event Arguments Common Properties BackColor Background color of control. SizeMode Controls image sizing and positioning (Normal. EventArgs.Windows. The images are named image0. and are located in directory images.Drawing.Forms. All Rights Reserved.gif. Fig. This image. event argument class Click EventHandler. Common Events Event delegate. 12. 12. 5 using System. autosized or centered). and the SizeMode property sets how the image is displayed (normal. The following program (Fig. can be in a bitmap. stretched. StretchImage. The reverse happens in the event handler for the vertical scrollbar (lines 69– 75). icon or metafile format (images and mul- timedia are discussed in Chapter 16).28) uses a PictureBox (named imagePic- tureBox) to display one of three bitmap images.ComponentModel. The Image property sets Image object to use. image1 and image2.jpg.

//add namespace 11 12 public class PictureBoxTest : System.NET generated code 27 28 // register event handler 29 30 this.ComponentModel.Forms. 7/5/01 . 42 System.EventHandler( 31 this.Image = Image.Form 13 { 14 private System. © Copyright 1992–2002 by Deitel & Associates. Chapter 12 Graphical User Interface Concepts: Part I 619 10 using System.Label promptLabel. Inc.Windows. 16 private int imageNum = -1. All Rights Reserved. 17 private System.Windows.IO. 18 19 public PictureBoxTest() 20 { 21 InitializeComponent().bmp" ).Container components = null. display on PictureBox 47 imagePictureBox. //imageNum from 0 to 2 45 46 // create Image object from file.Windows.28 Using a PictureBox to display images.EventArgs e ) 43 { 44 imageNum = ( imageNum + 1 ) % 3.imagePictureBox_Click ). 50 } 51 52 } // end class PictureBoxTest Fig. 22 } 23 24 private void InitializeComponent() 25 { 26 // Visual Studio.FromFile( 48 Directory. 12.imagePictureBox.PictureBox imagePictureBox.Run( new PictureBoxTest() ).Click += new System.GetCurrentDirectory() + "\\images\\image" + 49 imageNum + ".Forms. 15 private System. 32 } 33 34 [STAThread] 35 static void Main() 36 { 37 Application.Forms. 38 } 39 40 // change image whenever PictureBox clicked 41 private void imagePictureBox_Click( object sender.

IO. This returns the current directory of the exe- cutable file as a string.28. if we want to load image0 the string becomes “CurrentDir\images\image0. © Copyright 1992–2002 by Deitel & Associates. Finally.bmp”. 12. we must handle the Click event (line 41).28 Using a PictureBox to display images. 620 Graphical User Interface Concepts: Part I Chapter 12 Fig. we append “. This number stays between zero and two because of the modulus operator (line 37). To find the images we use class Directory (namespace System. Because we want the images subdirectory. We use imageNum to append the proper number. Thus. but we will overview a basic method now. image1 or image2. line 10) method GetCurrentDirectory (line 41). Class Image will be discussed in Chapter 16. 12.bmp”. where CurrentDir is the directory of the executable. initialized to -1 (line 16). so we can load either image0. To respond to the user’s clicks. Inside the event handler we use an integer (imageNum) to keep track of which image we want to dis- play. We then set the Image property of imagePictureBox to a valid Image. The result of clicking the PictureBox is seen at the end of the Fig. Method FromFile in class Image displays creates an Image object from a file whose path is passed as a string. 7/5/01 . All Rights Reserved. Inc. the type of the image. we append “\\images” followed by “\\” and then the file name.

presses. middle or none). right.29. relative to the component Fig.Chapter 12 Graphical User Interface Concepts: Part I 621 12. Delegates and Event Arguments Mouse Events (Delegate EventHandler. MouseLeave. MouseUp Mouse button released over control. is pressed down © Copyright 1992–2002 by Deitel & Associates. and the number of notches through which the mouse wheel turned. delegates and event arguments. Delegate MouseEventHandler. MouseUp and MouseMove events occur when the mouse enters or leaves a control. Mouse events can be handled for any GUI component that derives from class Sys- tem. X int. with the origin in the upper left corner of the control. event arguments EventArgs) MouseEnter Mouse enters control. Remember that each mouse event handling method must take an object and a MouseEventArgs object as param- eters.29 Mouse events. uses delegate EventHandler and event arguments EventArgs. Mouse event information is passed using class MouseEventArgs and the method to create the delegate is MouseEventHandler. MouseLeave Mouse leaves of control. MouseHover Mouse on top of control. Mouse Events.Control. Inc. Class MouseEventArgs contains information about the mouse event. Delta int. the button used.30) uses the mouse events to track actions of the mouse on the form.Windows. The number of notches (detents) through which the mouse wheel turned. The button that was pressed (left. The number of times the mouse was clicked. MouseEventArgs Properties Button enum MouseButtons. 12. The y-coordinate of the event.and y-coordinates are relative to the control that raised the event. the number of clicks.Forms. event arguments MouseEven- tArgs MouseDown Mouse pressed over control. MouseWheel Mouse wheel turned over control. relative to the component Y int. Note that the x. 7/5/01 . The various mouse events are described in Fig. The Click event. The MouseEnter. such as clicks. 12.9 Mouse Event Handling This section explains how to handle mouse events. Clicks int. All Rights Reserved. and moves. such as the x- and y-coordinates. MouseMove Mouse moved over control. The MouseTracker application (Fig. MouseDown. 12. which we have covered earlier. The x-coordinate of the event.

10 11 public class MouseTracker : System.Forms. 14 private System.Windows. When each event occurs it is displayed on a Label at the bottom of the form.Forms.EventHandler( 44 this. presses. 15 16 public MouseTracker() 17 { 18 InitializeComponent(). and moves). 5 using System. Inc.Forms.Form 12 { 13 private System. 41 42 this.MouseTracker_MouseEnter ). 29 30 this.ComponentModel.Windows.Windows. All Rights Reserved.Drawing. 45 } 46 47 [STAThread] 48 static void Main() 49 { 50 Application. 622 Graphical User Interface Concepts: Part I Chapter 12 or released or moved. 19 } 20 21 private void InitializeComponent() 22 { 23 // Visual Studio. 9 using System.MouseEventHandler( 28 this.Windows.Windows.MouseMove += 35 new System. and moves).MouseEventHandler( 32 this.MouseUp += 31 new System.MouseTracker_MouseUp ).Container components = null.MouseLeave += 43 new System.Forms.ComponentModel.MouseEventHandler( 36 this.MouseTracker_MouseLeave ).Forms. 33 34 this. 1 // MouseTracker.MouseTracker_MouseDown ).Label outputLabel.Run( new MouseTracker() ). 12.cs 2 // Demonstrating mouse events (clicks.MouseDown += 27 new System.30 Demonstrating mouse events (clicks.Data.MouseTracker_MouseMove ).EventHandler( 40 this. © Copyright 1992–2002 by Deitel & Associates.Forms. presses. 3 4 using System. 8 using System.Windows. 6 using System. 7/5/01 . Fig.MouseEnter += 39 new System. 37 38 this. respectively.NET generated code 24 25 // register event handlers 26 this.Collections. 7 using System.

" + e. 65 } 66 67 // event handler when mouse leaves form 68 protected void MouseTracker_MouseLeave( object sender.Y + "]". presses.Text = "Mouse outside Window".MouseEventArgs e ) 84 { 85 outputLabel. 69 System.Text = "Moved at [" + e.Y + "]". 58 } 59 60 // event handler when mouse moved 61 protected void MouseTracker_MouseMove( object sender. 55 System. All Rights Reserved. © Copyright 1992–2002 by Deitel & Associates. 72 } 73 74 // event handler when mouse enters window 75 protected void MouseTracker_MouseEnter( object sender.Windows. 62 System. 7/5/01 .EventArgs e ) 70 { 71 outputLabel. Inc. 86 } 87 88 } // end class MouseTracker Fig.Forms.30 Demonstrating mouse events (clicks.X + "." + e.Windows.EventArgs e ) 77 { 78 outputLabel. 76 System.Text = "Mouse in Window".Y + "]".Forms." + e.X + ".Text = "Pressed at [" + e. 12. 83 System.Forms.Windows. and moves).MouseEventArgs e ) 63 { 64 outputLabel. Chapter 12 Graphical User Interface Concepts: Part I 623 51 } 52 53 // event handler when mouse pressed then released 54 protected void MouseTracker_MouseUp( object sender.MouseEventArgs e ) 56 { 57 outputLabel. 79 } 80 81 // event handler when mouse pressed down (clicked) 82 protected void MouseTracker_MouseDown( object sender.X + ".Text = "Clicked at [" + e.

presses. The GUI consists of a single Label. 624 Graphical User Interface Concepts: Part I Chapter 12 Fig. Inc. called outputLabel. 12. which is on the bottom of the form. and moves).NET creates the mouse event handlers (lines 54–86) for the © Copyright 1992–2002 by Deitel & Associates. Visual Studio. 7/5/01 .30 Demonstrating mouse events (clicks. All Rights Reserved.

respectively.Chapter 12 Graphical User Interface Concepts: Part I 625 events we wanted to handle. at the bottom of the form. These events can be handled by any component that in- herits from System. Notice that Mou- seEnter and MouseLeave use the EventHandler delegate. not Mou- seEventHandler. © Copyright 1992–2002 by Deitel & Associates.10 Keyboard Event Handling This section explains how to handle key events. Inc. respectively (lines 75 and 68).Forms. and this can return a char for any ASCII character pressed (using KeyPressEventArgs property KeyChar). The key’s Key enumeration value can be re- turned. Class KeyEventArgs has information about special modifier keys. Alt and Control) were pressed.Windows. However. When any of the other events occur their handlers display a message in output- Label that includes a string that represents the event that occurred and the coordinates where the mouse event occurred. event handlers MouseTracker_MouseEnter and MouseTracker_MouseLeave are called. one cannot find out if special modifier keys (such as Shift. which form the second type. Figure 12. The events are those mentioned in the previous paragraph. 7/5/01 . giving information about a wide range of non-ASCII keys. There are two types of key events. Both methods display a message in outputLabel indi- cating that the mouse is inside or outside the application (see the first two screen captures).Control. 12. To do this. The x.and y-coordinates of the mouse when the event occurred are obtained with MouseEventArgs properties X and Y. The delegates for the two classes are KeyPressEventHandler (KeyPressEventArgs) and KeyEventHandler (KeyEventArgs). When the mouse enters or leaves the application area.31 lists important information about key events. The first is for event KeyPress. handle the KeyUp or KeyDown events. and each changes outputLabel. All Rights Reserved. Key events are generated when keys on the keyboard are pressed and released. and registered them as well (lines 26–44).

KeyEventArgs Properties Alt. KeyValue int. Control. Key Events (Delegate KeyPressEventHandler.Forms. All Rights Reserved. 8 using System.Collections.ComponentModel.32 demonstrates using the keyboard event handlers to display the key the user pressed. Returns the ASCII character that was pressed. KeyUp Key released. Inc. Handled bool.Windows. Control or Shift key was pressed. Fig. 9 using System. Whether or not KeyPress event handled. Returns the key code for the key. Handled bool. 7 using System. Delegates and Event Arguments Key Events (Delegate KeyEventHandler. 626 Graphical User Interface Concepts: Part I Chapter 12 Keyboard Events. combined with modifier information. © Copyright 1992–2002 by Deitel & Associates. 6 using System. The program is a form with two Labels and displays the key pressed along with any modifier information. Returns the key code as an int rather than a Keys enumeration. KeyData enum Keys.Data.32 Displaying information about the key the user pressed. delegates and event arguments. 3 4 using System.31 Keyboard events.Drawing. 12. KeyPressEventArgs Properties KeyChar char. Fig. Returns a Keys enumeration for any modifier keys (Alt. as a Keys enu- meration. as a Keys enumeration. 12. KeyCode enum Keys. Shift All bool. Modifiers enum Keys. event arguments KeyEventArgs) KeyDown Key initially pushed down. Returns the key code. This does not include modifier key information. Control. Figure 12. Whether or not the Alt.cs 2 // Displaying information about the key the user pressed. and Shift). event arguments KeyPressEventArgs) KeyPress Key pressed. 5 using System. keeps generating KeyPress events based on repeat rate. 7/5/01 . If key held down. 1 // KeyDemo. Can be set. Whether or not the event was handled.

Windows.Control ? "Yes" : "No" ) + '\n' + 59 "KeyCode: " + e.KeyDown += 28 new System.Forms.NET generated code 25 26 // register event handlers (note different delegates) 27 this.Forms.KeyEventArgs e) 54 { 55 keyInfoLabel.KeyPress += 31 new System.Form 12 { 13 private System. 14 private System. 49 } 50 51 // display modifier keys.32 Displaying information about the key the user pressed. 15 private System.Forms.Run( new KeyDemo() ). 12. Chapter 12 Graphical User Interface Concepts: Part I 627 10 11 public class KeyDemo : System.KeyUp += 34 new System.KeyCode + '\n' + 60 "KeyData: " + e.KeyData + '\n' + 61 "KeyValue: " + e.KeyDemo_KeyUp ). All Rights Reserved.Forms.Windows.Windows.Text = 56 "Alt: " + (e. 30 this.KeyChar.Windows.Shift ? "Yes" : "No" ) + '\n' + 58 "Ctrl: " + (e.Windows.Windows. 46 System. 7/5/01 .KeyDemo_KeyDown ). © Copyright 1992–2002 by Deitel & Associates.Label keyInfoLabel.Forms.ComponentModel. and key value 52 private void KeyDemo_KeyDown(object sender.Windows.Text = "Key pressed: " + e.KeyEventHandler( 29 this.Label charLabel. Inc. key code.KeyEventHandler( 35 this.Alt ? "Yes" : "No") + '\n' + 57 "Shift: " + (e.KeyValue.Forms.KeyPressEventArgs e ) 47 { 48 charLabel.KeyPressEventHandler( 32 this.Windows. 33 this.KeyDemo_KeyPress ).Container components = null. 36 } 37 38 [STAThread] 39 static void Main() 40 { 41 Application. 42 } 43 44 // display the character pressed using key char 45 protected void KeyDemo_KeyPress( object sender. key data.Forms. 62 } 63 Fig.Forms. 53 System. 20 } 21 22 private void InitializeComponent() 23 { 24 // Visual Studio. 16 17 public KeyDemo() 18 { 19 InitializeComponent().

which is implicitly converted to a string using method ToString. both capital and lowercase “a” are represented as the A key. which returns the key pressed as a char. This is displayed on charLabel. 12. all from its KeyEventArgs object. Shift and Control properties.Forms. The KeyCode property returns the key pressed. It then displays the KeyCode. Because the KeyDown and KeyPress events convey different information. 69 charLabel.Text = "". The KeyCode property returns a Keys enumeration. The two Labels (named charLabel and keyInfoLabel) are initially blank. The KeyPress event handler (line 45) accesses the KeyChar property of the Key- PressEventArgs object. If the key pressed was not an ASCII character then the KeyPress event will not fire and charLabel will be blank. The KeyDown event handler displays more information. 70 } 71 72 } // end class KeyDemo Fig. Inc. which return a boolean. Shift and Control keys (lines 56–58) using the Alt. 7/5/01 .Text = "". All Rights Reserved. 66 System. 628 Graphical User Interface Concepts: Part I Chapter 12 64 // clear labels when key released 65 private void KeyDemo_KeyUp( object sender. Thus. It tests for the Alt. but does not give any information about modifier keys.KeyEventArgs e ) 67 { 68 keyInfoLabel. © Copyright 1992–2002 by Deitel & Associates. KeyData and KeyValue properties. the form (KeyDemo) handles them both (lines 45–62).Windows.32 Displaying information about the key the user pressed.

• When the user interacts with a control it generates an event. KeyValue returns the key code for the key pressed as an integer. • GUIs are event driven. and can even represent mouse but- tons. • A control is a graphical component. The event informa- tion is then passed to event handlers. • A form is a graphical element that appears on the desktop. Visual Studio. because the KeyPress event was not generated.Chapter 12 Graphical User Interface Concepts: Part I 629 The KeyData property returns a Keys enumeration as well. components and controls are classes. The active window is the frontmost and has a blue title bar. Thus. When a user interaction occurs an event is generated. if capital “A” is input. A GUI (pronounced “GOO-EE”) gives a program a distinctive “look” and “feel. adding controls. 7/5/01 . Inc. • Use the Events window to create and register event handlers. This form can be a dialog box. The Visual Studio. SUMMARY • A graphical user interface (GUI) presents a pictorial interface to a program. Delegates act as an intermediate step between the object creating (raising) the event and the method handling it. • In many cases the programmer will simply handle the events generated by prepackaged controls. • GUIs are built from GUI components (sometimes called controls or widgets). A GUI component is a visual object with which the user interacts via the mouse or the keyboard. • The active window has the focus. The Keys enumeration can be used to test for specific keys by comparing it against the KeyCode. but includes data about modifier keys. setting their properties and configuring the event handlers. GUIs allow the user to spend more time using the program in a productive manner. • Windows Forms (previously called WinForms) create the GUI. The KeyDown event still fires and keyInfoLabel displays the important information. a window or a MDI window. • All forms. • The general design process for creating Windows applications involves creating a Windows Form. © Copyright 1992–2002 by Deitel & Associates. • Events in C# are based on the idea of delegates. the graphical interface to the pro- gram. All the programmer must do is create and register the event handler. All Rights Reserved. • The form acts as a container for the components that are added. KeyData will know that the A key and the Shift key were pressed.NET can create this code for us. such as a button. Non-control components are usually referred to simply as components. From the output. Lastly.” • By providing different applications with a consistent set of intuitive user interface components. This number is the Windows virtual key code.NET documentation has a complete list of the Keys enumeration. non-ASCII keys (such as F12) are not displayed in the upper char- Label. • In C#. • The information we need to register an event is the EventArgs class (to define the event handler) and the EventHandler delegate (to register the event handler). The KeyUp event handler clears both labels when the key is released (lines 68–69). a component is a class that implements the IComponent interface. settings its properties. This event can trigger methods that respond to the user’s actions.

which can either be blank or have a black checkmark. The main difference is that GroupBoxes can display text and Panels can have scrollbars. Buttons are used with the Click event. These events can be handled by any component that inherits from System. • Events KeyUp and KeyDown allow one to test for special modifier keys (using KeyEventArgs. • Class MouseEventArgs contains information about the x. One cannot find out if spe- cial modifier keys (such as Shift. A password text box only displays a certain character.NET generates a lot of code and we will hide the details of method Initialize- Component. create a method to call the delegate. • The KeyData property includes data about modifier keys. • Radio buttons and checkboxes use the CheckChanged event.Windows. indicated by the ^ symbol. KeyData and KeyValue properties. The delegates are KeyPressEventHandler (KeyPressEventArgs) and KeyEventHandler (KeyEventArgs). • A Button is a component the user clicks to trigger a specific action. Each GroupBox or Panel is its own group. • The KeyCode property returns the key pressed. create event handlers and register them. • Class KeyEventArgs has properties KeyCode. • A picture box (class PictureBox) displays an image (set by an object of class Image).Control. • Mouse events (clicks. the number of clicks and the number of notches through which the mouse wheel turned. Inc. © Copyright 1992–2002 by Deitel & Associates. presses and moves) can be handled for any GUI component that derives from System. Whenever scrollbars are changed they raise a Scroll event.Windows.630 Graphical User Interface Concepts: Part I Chapter 12 • The steps for creating an event are: create an event arguments class. • The KeyValue property returns the key code for the key pressed as an integer. All Rights Reserved.and y-coordinates. the button used.Forms.Control. define a delegate. • Key events are generated when keys on the keyboard are pressed and released. • Radio buttons (class RadioButton) have two states—selected and not selected. • A TextBox is a single-line area in which text can be entered. • Event KeyPress can return a char for any ASCII character pressed. • Labels (class Label) provide read-only text instructions or information on a GUI. Radio buttons appear as a group in which only one radio button can be selected at a time. • Visual C# has two types of state buttons— CheckBox and RadioButton—that have on/off or true/false values. • A checkbox is a small white square. Mouse events use class MouseEventArgs (MouseEventHandler delegate) and EventArgs (EventHandler delegate).Forms. • Scrollbars are intrinsic controls that allow the user to access a range of integer values. radio buttons must be added to GroupBoxes or Panels. • Visual Studio. • GroupBoxes and Panels help to arrange components on a GUI. 7/5/01 . To create new groups. There is no logical restriction on checkboxes. but does not give any information about modifier keys. Alt and Control) were pressed. • To easily toggle a single bit we use the bitwise exclusive OR operator (XOR). There are horizontal HScrollBars and vertical VScrollBars. create an event delegate reference.

pressing Enter mouse event event event argument event delegate event driven event handler event handler in Visual Studio. documentation event handler. remove event handling model event keyword event.NET focus Font property font style form Form class GetCurrentDirectory method © Copyright 1992–2002 by Deitel & Associates. All Rights Reserved. create event handler. register event handler.Chapter 12 Graphical User Interface Concepts: Part I 631 TERMINOLOGY active window Alt property ASCII character.NET event handler. create EventArgs class Events window in Visual Studio. Inc. 7/5/01 . naming event handler. test for background color button Button class button label checkbox CheckBox class checkbox label CheckedChanged event click a button Click event clicking the mouse closing a window combo box component container control Control property delegate deselected drag and drop drop-down list #endregion tag Enter key.

Inc. All Rights Reserved. 7/5/01 .632 Graphical User Interface Concepts: Part I Chapter 12 graphical user interface (GUI) GroupBox guess the number “guess the number” game GUI component handle event HScrollBar class Image property InitializeComponent method input data from the keyboard Internet Explorer key code key data key event key value keyboard KeyDown event KeyEventArgs class KeyPress event KeyPressEventArgs class KeyUp event label Label class list menu menu bar mouse mouse click mouse event mouse move mouse press MouseDown event MouseEventArgs class MouseEventHandler delegate MouseHover event MouseLeave event MouseMove event MouseUp event MouseWheel event moving the mouse multicast multicast events MulticastDelegate class mutually exclusive options Name property NewValue property not selected panel Panel class password box © Copyright 1992–2002 by Deitel & Associates.

Forms namespace text field Text property textbox TextBox class TextChanged event trigger an event typing in a text field uneditable text or icons virtual key code visual programming Visual Studio.NET generated code VScrollBar class widgets window gadgets Windows forms World Wide Web XOR. if false. components and controls are classes. using to toggle bit SELF-REVIEW EXERCISES 12. j) All mouse events use the same event arguments class. 7/5/01 . e) Events in C# are based on properties. All Rights Reserved. g) Buttons are commonly used to raise events.Chapter 12 Graphical User Interface Concepts: Part I 633 PasswordChar property picture box PictureBox class radio button radio button group RadioButton class raise event read-only text #region tag register event handler Scroll event scrollbar scrollbar in panel ScrollEventArgs class selecting an item from a menu Shift property SizeMode property System. k) Visual Studio.NET can register an event and create an empty event handler. a) A GUI is a pictorial interface to a program. f) Class Label is usually used to provide pictorial instructions or information.Windows. c) A control is a non-visible component. Inc. b) Windows Forms are commonly used to create a GUI. h) Checkboxes in the same group are mutually exclusive. © Copyright 1992–2002 by Deitel & Associates. i) Scrollbars allow the user to access a range of floating point values. d) All forms.1 State whether each of the following is true or false. explain why.

b) The form acts as a for the components that are added. Inc. 7/5/01 . f) A textbox only displays a single character (such as an asterisk) as the user types. You do not have to provide any functionality. b) container. h) False. © Copyright 1992–2002 by Deitel & Associates. Some mouse events use EventArgs. Radio buttons in the same group are mutually exclusive. e) The information we need to register an event handler is the class and the . d) signature. Panel. k) A event or delegate can call multiple methods. i) False. 12. Scrollbars can access in- teger values. g) GroupBox. e) event arguments. k) multicast. j) False. d) True. d) Every method that handles an event must have the same . f) False. as well as provide a logical group for radio buttons.2 a) focus.5 Create the following GUI. h) mouse clicks.634 Graphical User Interface Concepts: Part I Chapter 12 12. j) The modifier keys are . Class Label is used to provide text instructions or information. ANSWERS TO SELF-REVIEW EXERCISES 12. g) Class and class help to arrange components on a GUI. All Rights Reserved. k) True. You do not have to provide any functionality. j) Shift. EXERCISES 12.2 Fill in the blanks in each of the following statements. Events are based on delegates.4 Create the following GUI.22 to have a CheckBox for every font style option (Hint: Use XOR rather than testing for every bit explicitly). f) password. c) event. c) GUIs are driven.1 a) True.3 Extend the program in Figure 12. i) Key events. others use MouseEventArgs. Con- trol and Alt. b) True. h) Typical mouse events include . A control is a visible component. e) False. and . and . 12. 12. c) False. delegate. mouse presses and mouse moves. i) events are generated when the keyboard is pressed or released. g) True. a) The active window is said to have the .

All Rights Reserved. When the Button is clicked. The program then displays in a label: I have a number between 1 and 1000-can you guess my number? Please enter your first guess. Red indicates that the user is getting “warmer” and blue indicates that the user is getting “colder. 12.8 Write a program that plays “guess the number” as follows: Your program chooses the num- ber to be guessed by selecting an integer at random in the range 1–1000. When the user gets the correct answer. A Button should be provided to allow the user to play the game again. 7/5/01 . “Correct!” should be displayed and the TextBox used for input should be changed to uneditable.Chapter 12 Graphical User Interface Concepts: Part I 635 12. As each guess is input the background color should change to either red or blue. The Fahr- enheit temperature should be entered from the keyboard (via a TextBox). Inc. Use the following formula for the conversion: Celsius = (5/9) * (Fahrenheit . A Label should be used to display the converted temperature. a new random number should be generated and the input TextBox changed to editable. © Copyright 1992–2002 by Deitel & Associates.” A Label should display either “Too High” or “Too Low” to help the user zero in on the correct answer.6 Create the following GUI.32) 12. You do not have to provide any functionality.7 Write a temperature conversion program that converts from Fahrenheit to Celsius. A TextBox should be used to input the guess.

Inc. © Copyright 1992–2002 by Deitel & Associates.636 Graphical User Interface Concepts: Part I Chapter 12 [***NOTES TO REVIEWERS ***] • The discussion of control layout will be in Chapter 13. 7/5/01 . All Rights Reserved.

596 582 MouseWheel event 621 Click event 594 moving the mouse 585 GroupBox 601 clicking the mouse 585 multicast 586 guess the number 635 closing a window 585 multicast events 587 “guess the number” game 635 combo box 583 GUI component 582 MulticastDelegate class component 582. register 587 label 582. pressing 596 key data 629 event 585. 590 active window 584 EventArgs class 586. 596. 583. create 586 626 #region tag 600 event handler. 609 event driven 585 KeyDown event 626 radio button group 609 event handler 585 KeyEventArgs class 626 RadioButton class 609 event handler in Visual KeyPress event 626 raise event 586 Studio.NET 587 KeyPressEventArgs class read-only text 594 event handler. 605 G MouseHover event 621 CheckBox class 605 GetCurrentDirectory MouseLeave event 621 checkbox label 606 method 620 MouseMove event 621 CheckedChanged event 606 MouseUp event 621 graphical user interface (GUI) click a button 585. documentation 589 KeyUp event 626 register event handler 587 © Copyright 1992–2002 by Deitel & Associates. create new 587 Image property 618 deselected 609 InitializeComponent drag and drop 585 P method 588 drop-down list 583 input data from the keyboard 583 panel 583 Internet Explorer 582 Panel class 601 E password box 595 #endregion tag 600 PasswordChar property 599 Enter key.NET 587 menu bar 582 mouse 582 B mouse click 621 F mouse event 621 background color 635 focus 584 button 583 mouse move 621 Font property 608 Button class 596 mouse press 621 font style 606 button label 596 MouseDown event 621 form 584 MouseEventArgs class 621 Form class 585 MouseEventHandler delegate C 621 checkbox 583. 584 H Control property 628 handle event 586 HScrollBar class 614 N D Name property 599 NewValue property 617 delegate 586 I not selected 609 delegate. All Rights Reserved. create 589. 589 M Alt property 628 Events window in Visual menu 582 ASCII character. 584 586 container 583. remove 587 Label class 594 event handling model 585 list 583 event keyword 590 A event. naming 588 L #endregion tag 600 event handler. 594 #region tag 600 event handler.Index 1 Symbols event handler. Inc. pressing 596 K picture box 618 Enter mouse event 601 key code 628 PictureBox class 618 Escape key. test for 628 Studio. 7/5/01 . 584 mutually exclusive options 609 control 582. 586 key event 625. 626 event argument 586 key value 629 R event delegate 589 keyboard 582 radio button 596.

using to toggle bit 608 © Copyright 1992–2002 by Deitel & Associates.Forms namespace 585 T text field 582 Text property 599 textbox 583.2 Index S Scroll event 617 scrollbar 614 scrollbar in panel 602 ScrollEventArgs class 617 selecting an item from a menu 585 Shift property 628 SizeMode property 618 System.Windows. All Rights Reserved. 595 TextBox class 595 TextChanged event 595 trigger an event 583 typing in a text field 585 U uneditable text or icons 583 V virtual key code 629 visual programming 601 Visual Studio. Inc. 7/5/01 .NET generated code 600 VScrollBar class 614 W widgets 582 window gadgets 582 Windows forms 584 World Wide Web 582 X XOR.