graphical user interface concepts: part i

91
1 2006 Pearson Education, Inc. All rights rese 1 3 Graphical User Interface Concepts: Part I

Upload: kalin

Post on 23-Feb-2016

29 views

Category:

Documents


0 download

DESCRIPTION

13. Graphical User Interface Concepts: Part I. …the wisest prophets make sure of the event first. Horace Walpole. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Graphical User Interface Concepts: Part I

1

2006 Pearson Education, Inc. All rights reserved.

13

Graphical User Interface Concepts:

Part I

Page 2: Graphical User Interface Concepts: Part I

2

2006 Pearson Education, Inc. All rights reserved.

…the wisest prophets make sure of the event first.

— Horace Walpole

...The user should feel in control of the computer; not the other way around. This is achieved in applications that embody three qualities: responsiveness, permissiveness, and consistency.

— Inside Macintosh, Volume 1Apple Computer, Inc. 1985

All the better to see you with my dear.— The Big Bad Wolf to Little Red Riding Hood

Page 3: Graphical User Interface Concepts: Part I

3

2006 Pearson Education, Inc. All rights reserved.

OBJECTIVESIn this chapter you will learn: Design principles of graphical user interfaces (GUIs). How to create graphical user interfaces. How to process events that are generated by user

interactions with GUI controls. The namespaces that contain the classes for

graphical user interface controls and event handling. How to create and manipulate Button, Label, RadioButton, CheckBox, TextBox, Panel and NumericUpDown controls.

How to add descriptive ToolTips to GUI controls. How to process mouse and keyboard events.

Page 4: Graphical User Interface Concepts: Part I

4

2006 Pearson Education, Inc. All rights reserved.

13.1   Introduction13.2   Windows Forms13.3   Event Handling

13.3.1 A Simple Event-Driven GUI13.3.2 Another Look at the Visual Studio Generated

Code13.3.3 Delegates and the Event-Handling Mechanism13.3.4 Other Ways to Create Event Handlers13.3.5  Locating Event Information

13.4   Control Properties and Layout13.5   Labels, TextBoxes and Buttons

13.6   GroupBoxes and Panels

13.7   CheckBoxes and RadioButtons

13.8   PictureBoxes

Page 5: Graphical User Interface Concepts: Part I

5

2006 Pearson Education, Inc. All rights reserved.

13.9   ToolTips

13.10   NumericUpDown Control13.11   Mouse-Event Handling13.12   Keyboard-Event Handling13.13   Wrap-Up

Page 6: Graphical User Interface Concepts: Part I

6

2006 Pearson Education, Inc. All rights reserved.

13.1 Introduction

• Graphical User Interface (GUI)– Gives a program distinctive “look” and “feel”– Built from GUI controls (Fig. 13.2)

• Objects that can display information on the screen or enable users to interact with an application

• Implements IComponent interface

Page 7: Graphical User Interface Concepts: Part I

7

2006 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 13.1

Consistent user interfaces enable a user to learn new applications more quickly because the applications have the same “look” and “feel.”

Page 8: Graphical User Interface Concepts: Part I

8

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.1 | GUI controls in an Internet Explorer window.

Label Button Menu barTitle barMenu Combobox Scrollbar

Page 9: Graphical User Interface Concepts: Part I

9

2006 Pearson Education, Inc. All rights reserved.

Control Description

Label Displays images or uneditable text.

TextBox Enables the user to enter data via the keyboard. It can also be used to display editable or uneditable text.

Button Triggers an event when clicked with the mouse.

CheckBox Specifies an option that can be selected (checked) or unselected (not checked).

ComboBox Provides a drop-down list of items from which the user can make a selection either by clicking an item in the list or by typing in a box.

ListBox Provides a list of items from which the user can make a selection by clicking an item in the list. Multiple elements can be selected.

Panel A container in which controls can be placed and organized.

NumericUpDown Enables the user to select from a range of input values.

Fig. 13.2 | Some basic GUI controls.

Page 10: Graphical User Interface Concepts: Part I

10

2006 Pearson Education, Inc. All rights reserved.

13.2 Windows Forms

• Windows Forms– Used to create GUIs for programs– Graphical element that appears on your computer’s

desktop– Active window is the front most window– A Form is a container for controls and components– In visual programming, Visual Studio generates much of

the GUI-related code

Page 11: Graphical User Interface Concepts: Part I

11

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.3 | Components and controls for Windows Forms.

Display all controls and components

Categories that organize controls and components by functionality

Page 12: Graphical User Interface Concepts: Part I

12

2006 Pearson Education, Inc. All rights reserved.

Form properties, methods and events Description

Common Properties

AcceptButton Button that is clicked when Enter is pressed.

AutoScroll Boolean value that allows or disallows scrollbars when needed.

CancelButton Button that is clicked when the Escape key is pressed.

FormBorderStyle Border style for the Form (e.g., none, single, three-dimensional).

Font Font of text displayed on the Form, and the default font for controls added to the Form.

Text Text in the Form’s title bar.

Common Methods

Close Closes a Form and releases all resources, such as the memory used for the Form’s controls and components. A closed Form cannot be reopened.

Hide Hides a Form, but does not destroy the Form or release its resources.

Show Displays a hidden Form.

Common Event

Load Occurs before a Form is displayed to the user. The handler for this event is displayed in the Visual Studio editor when you double click the Form in the Visual Studio designer.

Fig. 13.4 | Common Form properties, methods and events.

Page 13: Graphical User Interface Concepts: Part I

13

2006 Pearson Education, Inc. All rights reserved.

13.3 Event Handling

• Event Handling– GUIs are event driven– When user interacts with a GUI component, the

interaction is known as an event– A method that performs a task in response to an event is

called an event handler

Page 14: Graphical User Interface Concepts: Part I

14

2006 Pearson Education, Inc. All rights reserved.

13.3.1 A Simple Event-Driven GUI

• Can create a Click event handler by double clicking the Button control on the Form (if applicable)

• By convention – Each variable name we create for a control ends with the

control’s type – C# names the event-handler method as controlName_eventName

(e.g., clickButton_Click) • Each event handler receives two parameters when called

– object named sender• A reference to the object that generated the event

– EventArgs named e • Contains additional information about the event that

occurred

Page 15: Graphical User Interface Concepts: Part I

15

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 13.5: SimpleEventExampleForm.cs 2 // Using Visual Studio to create event handlers. 3 using System; 4 using System.Windows.Forms; 5 6 // Form that shows a simple event handler 7 public partial class SimpleEventExampleForm : Form 8 { 9 // default constructor 10 public SimpleEventExampleForm() 11 { 12 InitializeComponent(); 13 } // end constructor 14 15 // handles click event of Button clickButton 16 private void clickButton_Click( object sender, EventArgs e ) 17 { 18 MessageBox.Show( "Button was clicked." ); 19 } // end method clickButton_Click 20 } // end class SimpleEventExampleForm

Outline

SimpleEventExampleForm.cs

The click event handler for clickButton

Let user know that clickButton was clicked by displaying MessageBox

Inherits from Form

Visual Studio generated InitializeComponent

Page 16: Graphical User Interface Concepts: Part I

16

2006 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 13.1

You should not expect return values from event handlers—event handlers are designed to execute code based on an action and return control to the main program.

Page 17: Graphical User Interface Concepts: Part I

17

2006 Pearson Education, Inc. All rights reserved.

Good Programming Practice 13.1

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

Page 18: Graphical User Interface Concepts: Part I

18

2006 Pearson Education, Inc. All rights reserved.

13.3.2 Another Look at the Visual Studio Generated Code

• Visual Studio Generated Code– The auto-generated code is saved in the Designer.cs file of

the Form– partial modifier allow the class created to be split

among multiple files– By default, all variable declarations for controls created

through C# have a private access modifier– The code also includes Dispose and InitializeComponent

Page 19: Graphical User Interface Concepts: Part I

19

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.6 | First half of the Visual Studio generated code file.

Page 20: Graphical User Interface Concepts: Part I

20

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.7 | Second half of the Visual Studio generated code file.

Page 21: Graphical User Interface Concepts: Part I

21

2006 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip 13.1

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

Page 22: Graphical User Interface Concepts: Part I

22

2006 Pearson Education, Inc. All rights reserved.

13.3.3 Delegates and the Event-Handling Mechanism

• Delegates and the Event-Handling Mechanism– Event sender

• Control that generates an event– Event receiver

• Responds to a particular event – Delegates

• Hold a reference to a method with a signature• delegate keyword• Multicast delegates

– Represent a set of delegate objects that all have same signature

Page 23: Graphical User Interface Concepts: Part I

23

2006 Pearson Education, Inc. All rights reserved.

13.3.4 Other Ways to Create Event Handlers

• Other ways to create event handlers– By double clicking a control, the Form creates a event

handler for that control– Able to create additional event handlers through the Properties window (Fig. 13.8)

Page 24: Graphical User Interface Concepts: Part I

24

2006 Pearson Education, Inc. All rights reserved.

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

Properties icon

Events icon

Selected events

Page 25: Graphical User Interface Concepts: Part I

25

2006 Pearson Education, Inc. All rights reserved.

13.3.5 Locating Event Information

• Read the Visual Studio documentation to learn about the different events raised (Fig. 13.9-13.10)

Page 26: Graphical User Interface Concepts: Part I

26

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.9 | List of Button events.

Class name List of events

Page 27: Graphical User Interface Concepts: Part I

27

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.10 | Click event details.

Event name

Event type

Event argument

class

Page 28: Graphical User Interface Concepts: Part I

28

2006 Pearson Education, Inc. All rights reserved.

13.4 Control Properties and Layout• Control Properties and Layout

– Focus method • Transfers the focus to a control and makes it the active control

– Enabled property • Indicates whether the user can interact with a control to generate an event

– Anchoring property • Causes controls to remain at a fixed distance from the sides of the container

(Fig. 13.12 – 13.13)– Docking property

• Attaches a control to a container such that the control stretches across an entire side (Fig. 13.14)

– Padding property • Specifies the distance between the docked controls and the Form edges

– Width and Height • Specifies size of Form

• Using Visual Studio To Edit GUI’s Layout– Snap lines

• Appear to help you position the control with respect to other controls

Page 29: Graphical User Interface Concepts: Part I

29

2006 Pearson Education, Inc. All rights reserved.

Class Control properties and methods Description

Common Properties

BackColor The control’s background color. BackgroundImage The control’s background image. Enabled Specifies whether the control is enabled (i.e., if the

user can interact with it). Typically, portions of a disabled control appear “grayed out” as a visual indication to the user that the control is disabled.

Focused Indicates whether the control has the focus. Font The Font used to display the control’s text. ForeColor The control’s foreground color. This usually

determines the color of the text in the Text property.

TabIndex The tab order of the control. When the Tab key is pressed, the focus transfers between controls based on the tab order. You can set this order.

TabStop If true, then a user can give focus to this control via the Tab key.

Fig. 13.11 | Class Control properties and methods. (Part 1 of 2)

Page 30: Graphical User Interface Concepts: Part I

30

2006 Pearson Education, Inc. All rights reserved.

Class Control properties and methods Description

TabStop If true, then a user can give focus to this control via the Tab key.

Text The text associated with the control. The location and appearance of the text vary depending on the type of control.

Visible Indicates whether the control is visible.

Common Methods

Focus Acquires the focus.

Hide Hides the control (sets the Visible property to false).

Show Shows the control (sets the Visible property to true).

Fig. 13.11 | Class Control properties and methods. (Part 2 of 2)

Page 31: Graphical User Interface Concepts: Part I

31

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.12 | Manipulating the Anchor property of a control.

Click down-arrow in Anchor property to display anchoring window

Anchoring window

Darkened bars indicate the container’s side(s) to which the control is anchored; use mouse clicks to select or deselect a bar

Page 32: Graphical User Interface Concepts: Part I

32

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.13 | Anchoring demonstration.

Constant distance to right and bottom sides

Before resizing After resizing

Page 33: Graphical User Interface Concepts: Part I

33

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.14 | Docking a Button to the top of a Form.

Before resizing After resizing

Control extends along entire top portion of form

Page 34: Graphical User Interface Concepts: Part I

34

2006 Pearson Education, Inc. All rights reserved.

Control layout properties Description

Anchor Causes a control to remain at a fixed distance from the side(s) of the container even when the container is resized.

Dock Allows a control to span one side of its container or to fill the entire container.

Padding Sets the space between a container’s edges and docked controls. The default is 0, causing the control to appear flush with the containe’s sides.

Location Specifies the location (as a set of coordinates) of the upper-left corner of the control, in relation to its container.

Size Specifies the size of the control in pixels as a Size object, which has properties Width and Height.

MinimumSize, MaximumSize

Indicates the minimum and maximum size of a Control, respectively.

Fig. 13.15 | Control layout properties.

Page 35: Graphical User Interface Concepts: Part I

35

2006 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 13.2

For resizable Forms, ensure that the GUI layout appears consistent across various Form sizes.

Page 36: Graphical User Interface Concepts: Part I

36

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.16 | Snap lines in Visual Studio 2005.

Snap line to help align controls on their left sides

Snap line that indicates when a control reaches the minimum recommended distance from the edge of a Form.

Page 37: Graphical User Interface Concepts: Part I

37

2006 Pearson Education, Inc. All rights reserved.

13.5 Labels, TextBoxes and Buttons

•Labels– Provide text information (as well as images)– Display text that user cannot directly modify – Can be changed programmatically

•TextBoxes– Area in which either text can be displayed or typed in– Password TextBoxes hides information entered by user

•Buttons– Control that user clicks to trigger specific action– There are several types of buttons, such as checkboxes and

radio buttons – All buttons derive from class ButtonBase

Page 38: Graphical User Interface Concepts: Part I

38

2006 Pearson Education, Inc. All rights reserved.

Common Label properties Description

Font The font of the text on the Label.

Text The text on the Label.

TextAlign The alignment of the Label’s text on the control—horizontally (left, center or right) and vertically (top, middle or bottom).

Fig. 13.17 | Common Label properties.

Page 39: Graphical User Interface Concepts: Part I

39

2006 Pearson Education, Inc. All rights reserved.

TextBox properties and events Description

Common Properties

AcceptsReturn If true in a multiline TextBox, pressing Enter in the TextBox creates a new line. If false, pressing Enter is the same as pressing the default Button on the Form. The default Button is the one assigned to a Form’s AcceptButton property.

Multiline If true, the TextBox can span multiple lines. The default value is false.

PasswordChar When this property is set to a character, the TextBox becomes a password box, and the specified character masks each character the user type. If no character is specified, the TextBox displays the typed text.

ReadOnly If true, the TextBox has a gray background, and its text cannot be edited. The default value is false.

ScrollBars For multiline textboxes, this property indicates which scrollbars appear (None, Horizontal, Vertical or Both).

Text The TextBox’s text content.

Common Event

TextChanged Generated when the text changes in a TextBox (i.e., when the user adds or deletes characters). When you double click the TextBox control in Design mode, an empty event handler for this event is generated.

Fig. 13.18 | TextBox properties and events.

Page 40: Graphical User Interface Concepts: Part I

40

2006 Pearson Education, Inc. All rights reserved.

Button properties and events Description

Common Properties

Text Specifies the text displayed on the Button face.

FlatStyle Modifies a Button’s appearance—attribute Flat (for the Button to display without a three-dimensional appearance), Popup (for the Button to appear flat until the user moves the mouse pointer over the Button), Standard (three-dimensional) and System, where the Button’s appearance is controlled by the operating system. The default value is Standard.

Common Event

Click Generated when the user clicks the Button. When you double click a Button in design view, an empty event handler for this event is created.

Fig. 13.19 | Button properties and event.

Page 41: Graphical User Interface Concepts: Part I

41

2006 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 13.3

Although Labels, TextBoxes and other controls can respond to mouse clicks, Buttons are more natural for this purpose.

Page 42: Graphical User Interface Concepts: Part I

42

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 13.20: LabelTextBoxButtonTestForm.cs 2 // Using a TextBox, Label and Button to display 3 // the hidden text in a password TextBox. 4 using System; 5 using System.Windows.Forms; 6 7 // Form that creates a password TextBox and 8 // a Label to display TextBox contents 9 public partial class LabelTextBoxButtonTestForm : Form 10 { 11 // default constructor 12 public LabelTextBoxButtonTestForm() 13 { 14 InitializeComponent(); 15 } // end constructor

Outline

LabelTextBoxButtonTestForm.cs

(1 of 2)

Page 43: Graphical User Interface Concepts: Part I

43

2006 Pearson Education, Inc. All rights reserved.

16 17 // display user input in Label 18 private void displayPasswordButton_Click( 19 object sender, EventArgs e ) 20 { 21 // display the text that the user typed 22 displayPasswordLabel.Text = inputPasswordTextBox.Text; 23 } // end method displayPasswordButton_Click 24 } // end class LabelTextBoxButtonTestForm

Outline

LabelTextBoxButtonTestForm.cs

(2 of 2)

The click event handler for displayPasswordButton

Display the password protected text in displayPasswordLabel

Page 44: Graphical User Interface Concepts: Part I

44

2006 Pearson Education, Inc. All rights reserved.

13.6 GroupBoxes and Panels

•GroupBoxes and Panels– Arrange controls on a GUI– Used to group similar functionality that a related– Primary difference between these two controls:

• GroupBoxes can display a caption (i.e., text) and do not include scrollbars

• Panels can include scrollbars and do not include a caption

Page 45: Graphical User Interface Concepts: Part I

45

2006 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 13.4

Panels and GroupBoxes can contain other Panels and GroupBoxes for more complex layouts.

Page 46: Graphical User Interface Concepts: Part I

46

2006 Pearson Education, Inc. All rights reserved.

GroupBox properties Description

Controls The set of controls that the GroupBox contains.

Text Specifies the caption text displayed at the top of the GroupBox.

Fig. 13.21 | GroupBox properties.

Page 47: Graphical User Interface Concepts: Part I

47

2006 Pearson Education, Inc. All rights reserved.

Panel properties Description

AutoScroll Indicates whether scrollbars appear when the Panel is too small to display all of its controls. The default value is false.

BorderStyle Sets the border of the Panel. The default value is None; other options are Fixed3D and FixedSingle.

Controls The set of controls that the Panel contains.

Fig. 13.22 | Panel properties.

Page 48: Graphical User Interface Concepts: Part I

48

2006 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 13.5

You can organize a GUI by anchoring and docking controls inside a GroupBox or Panel. The GroupBox or Panel then can be anchored or docked inside a Form. This divides controls into functional “groups” that can be arranged easily.

Page 49: Graphical User Interface Concepts: Part I

49

2006 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 13.6

Use Panels with scrollbars to avoid cluttering a GUI and to reduce the GUI’s size.

Page 50: Graphical User Interface Concepts: Part I

50

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.23 | Creating a Panel with scrollbars.

Control inside Panel

PanelScrollbars

Panel

Panelresized

Page 51: Graphical User Interface Concepts: Part I

51

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 13.24: GroupboxPanelExampleForm.cs 2 // Using GroupBoxes and Panels to hold Buttons. 3 using System; 4 using System.Windows.Forms; 5 6 // Form that displays a GroupBox and a Panel 7 public partial class GroupBoxPanelExampleForm : Form 8 { 9 // default constructor 10 public GroupBoxPanelExampleForm() 11 { 12 InitializeComponent(); 13 } // end constructor 14 15 // event handler for Hi Button 16 private void hiButton_Click( object sender, EventArgs e ) 17 { 18 messageLabel.Text = "Hi pressed"; // change text in Label 19 } // end method hiButton_Click 20 21 // event handler for Bye Button 22 private void byeButton_Click( object sender, EventArgs e ) 23 { 24 messageLabel.Text = "Bye pressed"; // change text in Label 25 } // end method byeButton_Click

Outline

GroupboxPanelExampleForm.cs

(1 of 2)

The click event handler for hiButton

The click event handler for byeButton

Change messageLabel’s text

Change messageLabel’s text

Page 52: Graphical User Interface Concepts: Part I

52

2006 Pearson Education, Inc. All rights reserved.

26 27 // event handler for Far Left Button 28 private void leftButton_Click( object sender, EventArgs e ) 29 { 30 messageLabel.Text = "Far left pressed"; // change text in Label 31 } // end method leftButton_Click 32 33 // event handler for Far Right Button 34 private void rightButton_Click( object sender, EventArgs e ) 35 { 36 messageLabel.Text = "Far right pressed"; // change text in Label 37 } // end method rightButton_Click 38 } // end class GroupBoxPanelExampleForm

Outline

GroupboxPanelExampleForm.cs

(2 of 2)

The click event handler for leftButton

Change messageLabel’s text

The click event handler for rightButton

Change messageLabel’s text

Page 53: Graphical User Interface Concepts: Part I

53

2006 Pearson Education, Inc. All rights reserved.

13.7 CheckBoxes and RadioButtons

• C# has two types of state buttons– CheckBoxes

• Small squares that either is blank or contains a check mark• Any number of CheckBoxes can be selected at a time• Font styles can be combined via bitwise operators

– RadioButtons• Only one can be selected at a time• Selecting one RadioButton in the group forces all the

others to be deselected. • RadioButtons represents a set of mutually exclusive

options

Page 54: Graphical User Interface Concepts: Part I

54

2006 Pearson Education, Inc. All rights reserved.

CheckBox properties and events Description

Common Properties

Checked Indicates whether the CheckBox is checked (contains a check mark) or unchecked (blank). This property returns a Boolean value.

CheckState Indicates whether the CheckBox is checked or unchecked with a value from the CheckState enumeration (Checked, Unchecked or Indeterminate). Indeterminate is used when it is unclear whether the state should be Checked or Unchecked. For example, in Microsoft Word, when you select a paragraph that contains several character formats, then go to Format > Font, some of the CheckBoxes appear in the Indeterminate state. When CheckState is set to Indeterminate, the CheckBox is usually shaded.

Text Specifies the text displayed to the right of the CheckBox.

Common Events

CheckedChanged Generated when the Checked property changes. This is a CheckBox’s default event. When a user double clicks the CheckBox control in design view, an empty event handler for this event is generated.

CheckStateChanged Generated when the CheckState property changes.

Fig. 13.25 | CheckBox properties and events.

Page 55: Graphical User Interface Concepts: Part I

55

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 13.26: CheckBoxTestForm.cs 2 // Using CheckBoxes to toggle italic and bold styles. 3 using System; 4 using System.Drawing; 5 using System.Windows.Forms; 6 7 // Form contains CheckBoxes to allow the user to modify sample text 8 public partial class CheckBoxTestForm : Form 9 { 10 // default constructor 11 public CheckBoxTestForm() 12 { 13 InitializeComponent(); 14 } // end constructor 15 16 // toggle the font style between bold and 17 // not bold based on the current setting 18 private void boldCheckBox_CheckedChanged( 19 object sender, EventArgs e ) 20 { 21 outputLabel.Font = 22 new Font( outputLabel.Font.Name, outputLabel.Font.Size, 23 outputLabel.Font.Style ^ FontStyle.Bold ); 24 } // end metod boldCheckBox_CheckedChanged

Outline

CheckBoxTestForm.cs

(1 of 2)

The event handler for boldCheckBox when user checks or unchecks

Bold the font of outputLabel if not done so already and vice versa

Page 56: Graphical User Interface Concepts: Part I

56

2006 Pearson Education, Inc. All rights reserved.

25 26 // toggle the font style between italic and 27 // not italic based on the current setting 28 private void italicCheckBox_CheckedChanged( 29 object sender, EventArgs e ) 30 { 31 outputLabel.Font = 32 new Font( outputLabel.Font.Name, outputLabel.Font.Size, 33 outputLabel.Font.Style ^ FontStyle.Italic ); 34 } // end method italicCheckBox_CheckedChanged 35 } // end class CheckBoxTestForm

Outline

CheckBoxTestForm.cs

(2 of 2)

The event handler for italicCheckBox when user checks or unchecks

Italicize the font of outputLabel if not done so already and vice versa

Page 57: Graphical User Interface Concepts: Part I

57

2006 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 13.7

Use RadioButtons when the user should choose only one option in a group.

Page 58: Graphical User Interface Concepts: Part I

58

2006 Pearson Education, Inc. All rights reserved.

Look-and-Feel Observation 13.8

Use CheckBoxes when the user should be able to choose multiple options in a group.

Page 59: Graphical User Interface Concepts: Part I

59

2006 Pearson Education, Inc. All rights reserved.

RadioButton properties and events Description

Common Properties

Checked Indicates whether the RadioButton is checked.

Text Specifies the RadioButton’s text. Common Event

CheckedChanged Generated every time the RadioButton is checked or unchecked. When you double click a RadioButton control in design view, an empty event handler for this event is generated.

Fig. 13.27 | RadioButton properties and events.

Page 60: Graphical User Interface Concepts: Part I

60

2006 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 13.2

Forms, GroupBoxes, and Panels can act as logical groups for RadioButtons. The RadioButtons within each group are mutually exclusive to each other, but not to RadioButtons in different logical groups.

Page 61: Graphical User Interface Concepts: Part I

61

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 13.28: RadioButtonsTestForm.cs 2 // Using RadioButtons to set message window options. 3 using System; 4 using System.Windows.Forms; 5 6 // Form contains several RadioButtons--user chooses one 7 // from each group to create a custom MessageBox 8 public partial class RadioButtonsTestForm : Form 9 { 10 // create variables that store the user's choice of options 11 private MessageBoxIcon iconType; 12 private MessageBoxButtons buttonType; 13 14 // default constructor 15 public RadioButtonsTestForm() 16 { 17 InitializeComponent(); 18 } // end constructor 19 20 // change Buttons based on option chosen by sender 21 private void buttonType_CheckedChanged( object sender, EventArgs e ) 22 { 23 if ( sender == okButton ) // display OK Button 24 buttonType = MessageBoxButtons.OK; 25 26 // display OK and Cancel Buttons 27 else if ( sender == okCancelButton ) 28 buttonType = MessageBoxButtons.OKCancel;

Outline

RadioButtonsTestForm.cs

(1 of 7)

Variables to determine how MessageBox will look like

Determine which buttons the user selected and store information in buttonType

Page 62: Graphical User Interface Concepts: Part I

62

2006 Pearson Education, Inc. All rights reserved.

29 30 // display Abort, Retry and Ignore Buttons 31 else if ( sender == abortRetryIgnoreButton ) 32 buttonType = MessageBoxButtons.AbortRetryIgnore; 33 34 // display Yes, No and Cancel Buttons 35 else if ( sender == yesNoCancelButton ) 36 buttonType = MessageBoxButtons.YesNoCancel; 37 38 // display Yes and No Buttons 39 else if ( sender == yesNoButton ) 40 buttonType = MessageBoxButtons.YesNo; 41 42 // only on option left--display Retry and Cancel Buttons 43 else 44 buttonType = MessageBoxButtons.RetryCancel; 45 } // end method buttonType_Changed 46 47 // change Icon based on option chosen by sender 48 private void iconType_CheckedChanged( object sender, EventArgs e ) 49 { 50 if ( sender == asteriskButton ) // display asterisk Icon 51 iconType = MessageBoxIcon.Asterisk; 52 53 // display error Icon 54 else if ( sender == errorButton ) 55 iconType = MessageBoxIcon.Error;

Outline

RadioButtonsTestForm.cs

(2 of 7)

Determine which buttons the user selected and store information in buttonType

Determine which icon the user selected and store information in iconType

Page 63: Graphical User Interface Concepts: Part I

63

2006 Pearson Education, Inc. All rights reserved.

56 57 // display exclamation point Icon 58 else if ( sender == exclamationButton ) 59 iconType = MessageBoxIcon.Exclamation; 60 61 // display hand Icon 62 else if ( sender == handButton ) 63 iconType = MessageBoxIcon.Hand; 64 65 // display information Icon 66 else if ( sender == informationButton ) 67 iconType = MessageBoxIcon.Information; 68 69 // display question mark Icon 70 else if ( sender == questionButton ) 71 iconType = MessageBoxIcon.Question; 72 73 // display stop Icon 74 else if ( sender == stopButton ) 75 iconType = MessageBoxIcon.Stop; 76 77 // only one option left--display warning Icon 78 else 79 iconType = MessageBoxIcon.Warning; 80 } // end method iconType_CheckChanged

Outline

RadioButtonsTestForm.cs

(3 of 7)

Determine which icon the user selected and store information in iconType

Page 64: Graphical User Interface Concepts: Part I

64

2006 Pearson Education, Inc. All rights reserved.

81 82 // display MessageBox and Button user pressed 83 private void displayButton_Click( object sender, EventArgs e ) 84 { 85 // display MessageBox and store 86 // the value of the Button that was pressed 87 DialogResult result = MessageBox.Show( 88 "This is your Custom MessageBox.", "Custom MessageBox", 89 buttonType, iconType, 0, 0 );

Outline

RadioButtonsTestForm.cs

(4 of 7)

The click event handler for displayButton

Display customized MessageBox

Page 65: Graphical User Interface Concepts: Part I

65

2006 Pearson Education, Inc. All rights reserved.

90 91 // check to see which Button was pressed in the MessageBox 92 // change text displayed accordingly 93 switch (result) 94 { 95 case DialogResult.OK: 96 displayLabel.Text = "OK was pressed."; 97 break; 98 case DialogResult.Cancel: 99 displayLabel.Text = "Cancel was pressed."; 100 break; 101 case DialogResult.Abort: 102 displayLabel.Text = "Abort was pressed."; 103 break; 104 case DialogResult.Retry: 105 displayLabel.Text = "Retry was pressed."; 106 break; 107 case DialogResult.Ignore: 108 displayLabel.Text = "Ignore was pressed."; 109 break; 110 case DialogResult.Yes: 111 displayLabel.Text = "Yes was pressed."; 112 break; 113 case DialogResult.No: 114 displayLabel.Text = "No was pressed."; 115 break; 116 } // end switch 117 } // end method displayButton_Click 118 } // end class RadioButtonsTestForm

Outline

RadioButtonsTestForm.cs

(5 of 7)

Test to see which button was pressed and change displayLabel’s text accordingly

Page 66: Graphical User Interface Concepts: Part I

66

2006 Pearson Education, Inc. All rights reserved.

Outline

RadioButtonsTestForm.cs

(6 of 7)

(c) OKCancel button type

(a) (b)

(e) AbortRetryIgnore button type

(d) OK button type

(f) YesNoCancel button type

Page 67: Graphical User Interface Concepts: Part I

67

2006 Pearson Education, Inc. All rights reserved.

Outline

RadioButtonsTestForm.cs

(7 of 7)

(h) RetryCancel button type(g) YesNo button type

Page 68: Graphical User Interface Concepts: Part I

68

2006 Pearson Education, Inc. All rights reserved.

13.8 PictureBoxes

•PictureBoxes– Display an image

Page 69: Graphical User Interface Concepts: Part I

69

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.29 | PictureBox properties and event.

PictureBox properties and event Description

Common Properties

Image Sets the image to display in the PictureBox.

SizeMode Enumeration that controls image sizing and positioning. Values are Normal (default), StretchImage, AutoSize and CenterImage. Normal places the image in the top-left corner of the PictureBox, and CenterImage puts the image in the middle. These two options truncate the image if it is too large. StretchImage resizes the image to fit in the PictureBox. AutoSize resizes the PictureBox to hold the image.

Common Event

Click Occurs when the user clicks the control. When you double click this control in the designer, an event handler is generated for this event.

Page 70: Graphical User Interface Concepts: Part I

70

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 13.30: PictureBoxTestForm.cs 2 // Using a PictureBox to display images. 3 using System; 4 using System.Drawing; 5 using System.Windows.Forms; 6 using System.IO; 7 8 // Form to display different images when PictureBox is clicked 9 public partial class PictureBoxTestForm : Form 10 { 11 private int imageNum = -1; // determines which image is displayed 12 13 // default constructor 14 public PictureBoxTestForm() 15 { 16 InitializeComponent(); 17 } // end constructor 18 19 // change image whenever Next Button is clicked 20 private void nextButton_Click( object sender, EventArgs e ) 21 { 22 imageNum = ( imageNum + 1 ) % 3; // imageNum cycles from 0 to 2 23 24 // create Image object from file, display in PicutreBox 25 imagePictureBox.Image = Image.FromFile( 26 Directory.GetCurrentDirectory() + @"\images\image" + 27 imageNum + ".bmp" ); 28 } // end method nextButton_Click 29 } // end class PictureBoxTestForm

Outline

PictureBoxTestForm.cs

(1 of 2)

Assign an image to the imagePictureBox given the specified directory

Page 71: Graphical User Interface Concepts: Part I

71

2006 Pearson Education, Inc. All rights reserved.

Outline

PictureBoxTestForm.cs

(2 of 2)

(a)

(b)

(c)

Page 72: Graphical User Interface Concepts: Part I

72

2006 Pearson Education, Inc. All rights reserved.

13.9 ToolTips

•ToolTips– Helpful text that appears when the mouse hovers over an

item

Page 73: Graphical User Interface Concepts: Part I

73

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.31 | ToolTip properties and events.

ToolTip properties and events Description

Common Properties

AutoPopDelay The amount of time (in milliseconds) that the tool tip appears while the mouse is over a control.

InitialDelay The amount of time (in milliseconds) that a mouse must hover over a control before a tool tip appears.

ReshowDelay The amount of time (in milliseconds) between which two different tool tips appear (when the mouse is moved from one control to another).

Common Event

Draw Raised when the tool tip is displayed. This event allows programmers to modify the appearance of the tool tip.

Page 74: Graphical User Interface Concepts: Part I

74

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 13.32: ToolTipExampleForm.cs 2 // Demonstrating the ToolTip component. 3 using System; 4 using System.Windows.Forms; 5 6 public partial class ToolTipExampleForm : Form 7 { 8 // default constructor 9 public ToolTipExampleForm() 10 { 11 InitializeComponent(); 12 } // end constructor 13 14 // no event handlers needed for this example 15

Outline

ToolTipExampleForm.cs

(a) (b)

Page 75: Graphical User Interface Concepts: Part I

75

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.33 | Demonstrating the component tray.

ToolTip in component tray

Page 76: Graphical User Interface Concepts: Part I

76

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.34 | Setting a control’s tool tip text.

Property to set tool tip text Tool tip text

Page 77: Graphical User Interface Concepts: Part I

77

2006 Pearson Education, Inc. All rights reserved.

13.10 NumericUpDown Control

•NumericUpDown– Restrict a user’s input choices to a specific range of

numeric values.– Appears as a TextBox, with two small Buttons on the

right side– NumericUpDown’s ReadOnly property indicates if user

can type a number into the control

Page 78: Graphical User Interface Concepts: Part I

78

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.35 | NumericUpDown properties and event.

NumericUpDown properties and event Description

Common Properties

Increment Specifies by how much the current number in the control changes when the user clicks the control’s up and down arrows.

Maximum Largest value in the control’s range.

Minimum Smallest value in the control’s range.

UpDownAlign Modifies the alignment of the up and down Buttons on the NumericUpDown control. This property can be used to display these Buttons either to the left or to the right of the control.

Value The numeric value currently displayed in the control.

Common Event

ValueChanged This event is raised when the value in the control is changed. This is the default event for the NumericUpDown control.

Page 79: Graphical User Interface Concepts: Part I

79

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 13.36: interestCalculatorForm.cs 2 // Demonstrating the NumericUpDown control. 3 using System; 4 using System.Windows.Forms; 5 6 public partial class interestCalculatorForm : Form 7 { 8 // default constructor 9 public interestCalculatorForm() 10 { 11 InitializeComponent(); 12 } // end constructor 13 14 private void calculateButton_Click( 15 object sender, EventArgs e ) 16 { 17 // declare variables to store user input 18 decimal principal; // store principal 19 double rate; // store interest rate 20 int year; // store number of years 21 decimal amount; // store amount 22 string output; // store output 23 24 // retrieve user input 25 principal = Convert.ToDecimal( principalTextBox.Text ); 26 rate = Convert.ToDouble( interestTextBox.Text ); 27 year = Convert.ToInt32( yearUpDown.Value );

Outline

interestCalculatorForm.cs

(1 of 2)

Retrieve, convert, and assign principalTextBox, InterestTextBox, and yearUpDown’s values

Page 80: Graphical User Interface Concepts: Part I

80

2006 Pearson Education, Inc. All rights reserved.

28 29 // set output header 30 output = "Year\tAmount on Deposit\r\n"; 31 32 // calculate amount after each year and append to output 33 for ( int yearCounter = 1; yearCounter <= year; yearCounter++ ) 34 { 35 amount = principal * 36 ( ( decimal ) Math.Pow( ( 1 + rate / 100 ), yearCounter ) ); 37 output += ( yearCounter + "\t" + 38 string.Format( "{0:C}", amount ) + "\r\n" ); 39 } // end for 40 41 displayTextBox.Text = output; // display result 42 } // end method calculateButton_Click 43 } // end class interestCalculatorForm

Outline

interestCalculatorForm.cs

(2 of 2)

Click to increase number of years

Click to decreasenumber of years

NumericalUpDown control

Calculate interest and format it as a String

Output results in displayTextBox

Page 81: Graphical User Interface Concepts: Part I

81

2006 Pearson Education, Inc. All rights reserved.

13.11 Mouse-Event Handling

• Mouse-Event Handling– Mouse events can be handled for any control that derives

from class System.Windows.Forms.Control– Class MouseEventArgs

• Contains information related to the mouse event• Information about the event is passed to the event-handling

method through an object of this class– The delegate used to create the mouse-event handlers is MouseEventHandler

Page 82: Graphical User Interface Concepts: Part I

82

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.37 | Mouse events and event arguments. (Part 1 of 2.)

Mouse events and event arguments

Mouse Events with Event Argument of Type EventArgs

MouseEnter Occurs when the mouse cursor enters the control’s boundaries.

MouseLeave Occurs when the mouse cursor leaves the control’s boundaries.

Mouse Events with Event Argument of Type MouseEventArgs

MouseDown Occurs when a mouse button is pressed while the mouse cursor is within a control’s boundaries.

MouseHover Occurs when the mouse cursor hovers within the control’s boundaries.

MouseMove Occurs when the mouse cursor is moved while in the control’s boundaries.

MouseUp Occurs when a mouse button is released when the cursor is over the control’s boundaries.

Page 83: Graphical User Interface Concepts: Part I

83

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.37 | Mouse events and event arguments. (Part 2 of 2.)

Mouse events and event arguments

Class MouseEventArgs Properties

Button Specifies which mouse button was pressed (Left, Right, Middle or none).

Clicks The number of times that the mouse button was clicked.

X The x-coordinate within the control where the event occurred.

Y The y-coordinate within the control where the event occurred.

Page 84: Graphical User Interface Concepts: Part I

84

2006 Pearson Education, Inc. All rights reserved.

1 // Fig 13.38: PainterForm.cs 2 // Using the mouse to draw on a Form. 3 using System; 4 using System.Drawing; 5 using System.Windows.Forms; 6 7 // creates a Form that is a drawing surface 8 public partial class PainterForm : Form 9 { 10 bool shouldPaint = false; // determines whether to paint 11 12 // default constructor 13 public PainterForm() 14 { 15 InitializeComponent(); 16 } // end constructor 17 18 // should paint when mouse button is pressed down 19 private void PainterForm_MouseDown( object sender, MouseEventArgs e ) 20 { 21 // indicate that user is dragging the mouse 22 shouldPaint = true; 23 } // end method PainterForm_MouseDown 24 25 // stop painting when mouse button is released 26 private void PainterForm_MouseUp( object sender, MouseEventArgs e ) 27 { 28 // indicate that user released the mouse button 29 shouldPaint = false; 30 } // end method PainterForm_MouseUp

Outline

PainterForm.cs

(1 of 2)

Default instance variable to false to identify that painting will not occur

Set shouldPaint to true to identify that painting will occur

Set shouldPaint to false to identify that painting will not occur

Page 85: Graphical User Interface Concepts: Part I

85

2006 Pearson Education, Inc. All rights reserved.

31 32 // draw circle whenever mouse moves with its button held down 33 private void PainterForm_MouseMove( object sender, MouseEventArgs e ) 34 { 35 if ( shouldPaint ) // check if mouse button is being pressed 36 { 37 // draw a circle where the mouse pointer is present 38 Graphics graphics = CreateGraphics(); 39 graphics.FillEllipse( 40 new SolidBrush( Color.BlueViolet ), e.X, e.Y, 4, 4 ); 41 graphics.Dispose(); 42 } // end if 43 } // end method PainterForm_MouseMove 44 } // end class PainterForm

Outline

PainterForm.cs

(1 of 2)Paint on the Form when mouse is being pressed

Page 86: Graphical User Interface Concepts: Part I

86

2006 Pearson Education, Inc. All rights reserved.

13.12 Keyboard-Event Handling

• Keyboard-Event Handling– Key events occur when keyboard keys are pressed and released– There are three key events:

• KeyPress– The event occurs when the user presses a key that represents

an ASCII character• The specific key can be determined with property KeyChar of the event handler’s KeyPressEventArgs argument

• Does not indicate whether modifier keys were pressed• KeyUp and KeyDown

– If information about the modifier keys are important, use the KeyUp or KeyDown events

• The KeyEventArgs argument for each of these events contains information about modifier keys.

Page 87: Graphical User Interface Concepts: Part I

87

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.39 | Keyboard events and event arguments. (Part 1 of 2.)

Keyboard events and event arguments

Key Events with Event Arguments of Type KeyEventArgs

KeyDown Generated when a key is initially pressed.

KeyUp Generated when a key is released.

Key Event with Event Argument of Type KeyPressEventArgs

KeyPress Generated when a key is pressed.

Class KeyPressEventArgs Properties

KeyChar Returns the ASCII character for the key pressed.

Handled Indicates whether the KeyPress event was handled.

Class KeyEventArgs Properties

Alt Indicates whether the Alt key was pressed.

Control Indicates whether the Ctrl key was pressed.

Shift Indicates whether the Shift key was pressed.

Handled Indicates whether the event was handled.

Page 88: Graphical User Interface Concepts: Part I

88

2006 Pearson Education, Inc. All rights reserved.

Fig. 13.39 | Keyboard events and event arguments. (Part 2 of 2.)

Keyboard events and event arguments

KeyCode Returns the key code for the key as a value from the Keys enumeration. This does not include modifier-key information. It is used to test for a specific key.

KeyData Returns the key code for a key combined with modifier information as a Keys value. This property contains all information about the pressed key.

KeyValue Returns the key code as an int, rather than as a value from the Keys enumeration. This property is used to obtain a numeric representation of the pressed key. The int value is known as a Windows virtual key code.

Modifiers Returns a Keys value indicating any pressed modifier keys (Alt, Ctrl and Shift). This property is used to determine modifier-key information only.

Page 89: Graphical User Interface Concepts: Part I

89

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 13.40: KeyDemoForm.cs 2 // Displaying information about the key the user pressed. 3 using System; 4 using System.Windows.Forms; 5 6 // Form to display key information when key is pressed 7 public partial class KeyDemoForm : Form 8 { 9 // default constructor 10 public KeyDemoForm() 11 { 12 InitializeComponent(); 13 } // end constructor 14 15 // display the character pressed using KeyChar 16 private void KeyDemoForm_KeyPress( object sender, KeyPressEventArgs e ) 17 { 18 charLabel.Text = "Key pressed: " + e.KeyChar; 19 } // end method KeyDemoForm_KeyPress

Outline

KeyDemoForm.cs

(1 of 3)

Property that returns the ASCII character for the key pressed

Page 90: Graphical User Interface Concepts: Part I

90

2006 Pearson Education, Inc. All rights reserved.

20 21 // display modifier keys, key code, key data and key value 22 private void KeyDemoForm_KeyDown( object sender, KeyEventArgs e ) 23 { 24 keyInfoLabel.Text = 25 "Alt: " + ( e.Alt ? "Yes" : "No" ) + '\n' + 26 "Shift: " + ( e.Shift ? "Yes" : "No" ) + '\n' + 27 "Ctrl: " + ( e.Control ? "Yes" : "No" ) + '\n' + 28 "KeyCode: " + e.KeyCode + '\n' + 29 "KeyData: " + e.KeyData + '\n' + 30 "KeyValue: " + e.KeyValue; 31 } // end method KeyDemoForm_KeyDown 32 33 // clear Labels when key released 34 private void KeyDemoForm_KeyUp( object sender, KeyEventArgs e ) 35 { 36 charLabel.Text = ""; 37 keyInfoLabel.Text = ""; 38 } // end method KeyDemoForm_KeyUp 39 } // end class KeyDemoForm

Outline

KeyDemoForm.cs

(2 of 3)

Reset labels

Return the key code for the key as a value from the Keys enumerations

Returns the key code for a key combined with modifier information as a Key value

Returns key code as an int

Page 91: Graphical User Interface Concepts: Part I

91

2006 Pearson Education, Inc. All rights reserved.

Outline

KeyDemoForm.cs

(3 of 3)

(c) $ pressed

(a) H pressed

(b) F12 pressed

(d) Enter pressed