Sunteți pe pagina 1din 91

1

13
Graphical User
Interface Concepts:
Part I
 2006 Pearson Education, Inc. All rights reserved.
2

…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 1
Apple Computer, Inc. 1985

All the better to see you with my dear.


— The Big Bad Wolf to Little Red Riding Hood

 2006 Pearson Education, Inc. All rights reserved.


3

OBJECTIVES
In 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.

 2006 Pearson Education, Inc. All rights reserved.


4

13.1 Introduction
13.2 Windows Forms
13.3 Event Handling
13.3.1 A Simple Event-Driven GUI
13.3.2 Another Look at the Visual Studio Generated
Code
13.3.3 Delegates and the Event-Handling Mechanism
13.3.4 Other Ways to Create Event Handlers
13.3.5 Locating Event Information
13.4 Control Properties and Layout
13.5 Labels, TextBoxes and Buttons
13.6 GroupBoxes and Panels
13.7 CheckBoxes and RadioButtons
13.8 PictureBoxes

 2006 Pearson Education, Inc. All rights reserved.


5

13.9 ToolTips
13.10 NumericUpDown Control
13.11 Mouse-Event Handling
13.12 Keyboard-Event Handling
13.13 Wrap-Up

 2006 Pearson Education, Inc. All rights reserved.


6

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

 2006 Pearson Education, Inc. All rights reserved.


7

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.”

 2006 Pearson Education, Inc. All rights reserved.


8

Label Button Menu Title bar Menu bar Combobox


Scrollbar

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

 2006 Pearson Education, Inc. All rights reserved.


9

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.

 2006 Pearson Education, Inc. All rights reserved.


10

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

 2006 Pearson Education, Inc. All rights reserved.


11

Display all
controls and
components

Categories that
organize
controls and
components by
functionality

Fig. 13.3 | Components and controls for Windows Forms.

 2006 Pearson Education, Inc. All rights reserved.


12

Form properties, methods


Description
and events

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.

 2006 Pearson Education, Inc. All rights reserved.


13

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

 2006 Pearson Education, Inc. All rights reserved.


14

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

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 13.5: SimpleEventExampleForm.cs 15
2 // Using Visual Studio to create event handlers. Outline
3 using System;
4 using System.Windows.Forms; Inherits from Form
5
6 // Form that shows a simple event handler
SimpleEventExample
7 public partial class SimpleEventExampleForm : Form
Form.cs
8 {
9 // default constructor Visual Studio generated
10 public SimpleEventExampleForm() InitializeComponent
11 {
12 InitializeComponent(); The click event handler for clickButton
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 Let user know that clickButton was
clicked by displaying MessageBox

 2006 Pearson Education,


Inc. All rights reserved.
16

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.

 2006 Pearson Education, Inc. All rights reserved.


17

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.

 2006 Pearson Education, Inc. All rights reserved.


18

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

 2006 Pearson Education, Inc. All rights reserved.


19

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

 2006 Pearson Education, Inc. All rights reserved.


20

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

 2006 Pearson Education, Inc. All rights reserved.


21

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.

 2006 Pearson Education, Inc. All rights reserved.


22

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

 2006 Pearson Education, Inc. All rights reserved.


23

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)

 2006 Pearson Education, Inc. All rights reserved.


24
Properties icon

Events icon

Selected events

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

 2006 Pearson Education, Inc. All rights reserved.


25

13.3.5 Locating Event Information

• Read the Visual Studio documentation to learn


about the different events raised (Fig. 13.9-13.10)

 2006 Pearson Education, Inc. All rights reserved.


26

Class name List of events

Fig. 13.9 | List of Button events.

 2006 Pearson Education, Inc. All rights reserved.


27

Event name

Event type

Event argument

class

Fig. 13.10 | Click event details.

 2006 Pearson Education, Inc. All rights reserved.


28

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

 2006 Pearson Education, Inc. All rights reserved.


29
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)

 2006 Pearson Education, Inc. All rights reserved.


30

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)

 2006 Pearson Education, Inc. All rights reserved.


31

Anchoring
window

Click down-arrow
in Anchor
property to display
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

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

 2006 Pearson Education, Inc. All rights reserved.


32

Before resizing After resizing

Constant distance
to right and bottom
sides

Fig. 13.13 | Anchoring demonstration.

 2006 Pearson Education, Inc. All rights reserved.


33

After resizing
Before resizing

Control extends along


entire top portion of form

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

 2006 Pearson Education, Inc. All rights reserved.


34

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, Indicates the minimum and maximum size of a
MaximumSize Control, respectively.

Fig. 13.15 | Control layout properties.

 2006 Pearson Education, Inc. All rights reserved.


35

Look-and-Feel Observation 13.2

For resizable Forms, ensure that the GUI layout


appears consistent across various Form sizes.

 2006 Pearson Education, Inc. All rights reserved.


36

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.

Fig. 13.16 | Snap lines in Visual Studio 2005.

 2006 Pearson Education, Inc. All rights reserved.


37

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

 2006 Pearson Education, Inc. All rights reserved.


38

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.

 2006 Pearson Education, Inc. All rights reserved.


39

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.

 2006 Pearson Education, Inc. All rights reserved.


40

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.

 2006 Pearson Education, Inc. All rights reserved.


41

Look-and-Feel Observation 13.3

Although Labels, TextBoxes and other controls


can respond to mouse clicks, Buttons are more
natural for this purpose.

 2006 Pearson Education, Inc. All rights reserved.


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

 2006 Pearson Education,


Inc. All rights reserved.
16 43
17 // display user input in Label
18 private void displayPasswordButton_Click(
Outline
19 object sender, EventArgs e ) The click event handler for
20 { displayPasswordButton
21 // display the text that the user typed
22 displayPasswordLabel.Text = inputPasswordTextBox.Text; LabelTextBoxButton
23 } // end method displayPasswordButton_Click TestForm.cs
24 } // end class LabelTextBoxButtonTestForm
Display the password
(2 ofprotected
2) text
in displayPasswordLabel

 2006 Pearson Education,


Inc. All rights reserved.
44

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

 2006 Pearson Education, Inc. All rights reserved.


45

Look-and-Feel Observation 13.4

Panels and GroupBoxes can contain other


Panels and GroupBoxes for more complex
layouts.

 2006 Pearson Education, Inc. All rights reserved.


46

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.

 2006 Pearson Education, Inc. All rights reserved.


47

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.

 2006 Pearson Education, Inc. All rights reserved.


48

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.

 2006 Pearson Education, Inc. All rights reserved.


49

Look-and-Feel Observation 13.6

Use Panels with scrollbars to avoid cluttering a


GUI and to reduce the GUI’s size.

 2006 Pearson Education, Inc. All rights reserved.


50

Control inside
Panel

Panel

Panel
Scrollbars
Panel
resized

Fig. 13.23 | Creating a Panel with scrollbars.

 2006 Pearson Education, Inc. All rights reserved.


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

Change messageLabel’s text

 2006 Pearson Education,


Inc. All rights reserved.
26 52
27 // event handler for Far Left Button The click event handler for leftButton
28 private void leftButton_Click( object sender, EventArgs e )
Outline
29 { Change messageLabel’s text
30 messageLabel.Text = "Far left pressed"; // change text in Label
31 } // end method leftButton_Click
32
33 // event handler for Far Right Button
The click event handlerGroupboxPanelExamp
for rightButton
leForm.cs
34 private void rightButton_Click( object sender, EventArgs e )
35 {
36 messageLabel.Text = "Far right pressed"; // change text in Label
(2 of 2)
37 } // end method rightButton_Click
38 } // end class GroupBoxPanelExampleForm
Change messageLabel’s text

 2006 Pearson Education,


Inc. All rights reserved.
53

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

 2006 Pearson Education, Inc. All rights reserved.


54

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.

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 13.26: CheckBoxTestForm.cs 55
2 // Using CheckBoxes to toggle italic and bold styles.
3 using System;
Outline
4 using System.Drawing;
5 using System.Windows.Forms;
6
7 // Form contains CheckBoxes to allow the user to modify sample text CheckBoxTestForm
8 public partial class CheckBoxTestForm : Form .cs
9 {
10 // default constructor (1 of 2)
11 public CheckBoxTestForm()
12 {
13 InitializeComponent();
14 } // end constructor
15
16 // toggle the font style between bold and The event handler for boldCheckBox
17 // not bold based on the current setting
18 private void boldCheckBox_CheckedChanged(
when user checks or unchecks
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

Bold the font of outputLabel if not


done so already and vice versa

 2006 Pearson Education,


Inc. All rights reserved.
25
56
// toggle the font style between italic and
26
The event handler for italicCheckBox
Outline
27 // not italic based on the current setting
28 private void italicCheckBox_CheckedChanged( when user checks or unchecks
29 object sender, EventArgs e )
30 {
31 outputLabel.Font =
32 new Font( outputLabel.Font.Name, outputLabel.Font.Size, CheckBoxTestForm
33 outputLabel.Font.Style ^ FontStyle.Italic ); .cs
34 } // end method italicCheckBox_CheckedChanged
35 } // end class CheckBoxTestForm Italicize the font of outputLabel if
(2 of 2)
not done so already and vice versa

 2006 Pearson Education,


Inc. All rights reserved.
57

Look-and-Feel Observation 13.7

Use RadioButtons when the user should choose


only one option in a group.

 2006 Pearson Education, Inc. All rights reserved.


58

Look-and-Feel Observation 13.8

Use CheckBoxes when the user should be able to


choose multiple options in a group.

 2006 Pearson Education, Inc. All rights reserved.


59

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.

 2006 Pearson Education, Inc. All rights reserved.


60

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.

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 13.28: RadioButtonsTestForm.cs 61
2 // Using RadioButtons to set message window options.
3 using System;
Outline
4 using System.Windows.Forms;
5
6 // Form contains several RadioButtons--user chooses one
7 // from each group to create a custom MessageBox RadioButtonsTest
8 public partial class RadioButtonsTestForm : Form Form.cs
9 {
10 // create variables that store the user's choice of options (1 of 7)
11 private MessageBoxIcon iconType;
12 private MessageBoxButtons buttonType;
Variables
to determine how
13 MessageBox will look like
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; Determine which buttons the
25 user selected and store
26 // display OK and Cancel Buttons
information in buttonType
27 else if ( sender == okCancelButton )
28 buttonType = MessageBoxButtons.OKCancel;

 2006 Pearson Education,


Inc. All rights reserved.
29 62
30 // display Abort, Retry and Ignore Buttons
31 else if ( sender == abortRetryIgnoreButton )
Outline
32 buttonType = MessageBoxButtons.AbortRetryIgnore;
33
34 // display Yes, No and Cancel Buttons
35 else if ( sender == yesNoCancelButton ) RadioButtonsTest
Determine which buttons the
36 buttonType = MessageBoxButtons.YesNoCancel; Form.cs
user selected and store
37
38 // display Yes and No Buttons
information
(2 of buttonType
in 7)
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
Determine which icon the user
53 // display error Icon selected and store information
54 else if ( sender == errorButton ) in iconType
55 iconType = MessageBoxIcon.Error;

 2006 Pearson Education,


Inc. All rights reserved.
56 63
57 // display exclamation point Icon
58 else if ( sender == exclamationButton )
Outline
59 iconType = MessageBoxIcon.Exclamation;
60
61 // display hand Icon
62 else if ( sender == handButton ) RadioButtonsTest
63 iconType = MessageBoxIcon.Hand; Form.cs
64
65 // display information Icon (3 of 7)
66 else if ( sender == informationButton )
67 iconType = MessageBoxIcon.Information;
68
Determine which icon the user
69 // display question mark Icon
70 else if ( sender == questionButton )
selected and store information
71 iconType = MessageBoxIcon.Question; in iconType
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

 2006 Pearson Education,


Inc. All rights reserved.
81 64
82 // display MessageBox and Button user pressed Outline
83 private void displayButton_Click( object sender, EventArgs e )
84 {
The click event handler for
85 // display MessageBox and store
displayButton
86 // the value of the Button that was pressed
RadioButtonsTest
87 DialogResult result = MessageBox.Show(
Form.cs
88 "This is your Custom MessageBox.", "Custom MessageBox",
89 buttonType, iconType, 0, 0 ); (4 of 7)
Display customized MessageBox

 2006 Pearson Education,


Inc. All rights reserved.
90 65
91 // check to see which Button was pressed in the MessageBox
92 // change text displayed accordingly
Outline
93 switch (result)
Test to see which button was pressed and change
94 {
95 case DialogResult.OK:
displayLabel’s text accordingly
96 displayLabel.Text = "OK was pressed."; RadioButtonsTest
97 break; Form.cs
98 case DialogResult.Cancel:
99 displayLabel.Text = "Cancel was pressed."; (5 of 7)
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

 2006 Pearson Education,


Inc. All rights reserved.
66
(a) (b) Outline

RadioButtonsTest
Form.cs

(6 of 7)

(c) OKCancel button type (d) OK button type

(e) AbortRetryIgnore button type (f) YesNoCancel button type

 2006 Pearson Education,


Inc. All rights reserved.
67
(g) YesNo button type (h) RetryCancel button type Outline

RadioButtonsTest
Form.cs

(7 of 7)

 2006 Pearson Education,


Inc. All rights reserved.
68

13.8 PictureBoxes

•PictureBoxes
– Display an image

 2006 Pearson Education, Inc. All rights reserved.


69

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.

Fig. 13.29 | PictureBox properties and event.

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 13.30: PictureBoxTestForm.cs 70
2 // Using a PictureBox to display images.
3 using System;
Outline
4 using System.Drawing;
5 using System.Windows.Forms;
6 using System.IO;
7 PictureBoxTestForm
8 // Form to display different images when PictureBox is clicked .cs
9 public partial class PictureBoxTestForm : Form
10 { (1 of 2)
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" + Assign an image to the
27 imageNum + ".bmp" ); imagePictureBox given
28 } // end method nextButton_Click the specified directory
29 } // end class PictureBoxTestForm

 2006 Pearson Education,


Inc. All rights reserved.
71
(a) Outline

(b)

PictureBoxTestForm
.cs

(2 of 2)

(c)

 2006 Pearson Education,


Inc. All rights reserved.
72

13.9 ToolTips

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

 2006 Pearson Education, Inc. All rights reserved.


73

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.

Fig. 13.31 | ToolTip properties and events.

 2006 Pearson Education, Inc. All rights reserved.


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

(a) (b)

 2006 Pearson Education,


Inc. All rights reserved.
75

ToolTip in
component tray

Fig. 13.33 | Demonstrating the component tray.

 2006 Pearson Education, Inc. All rights reserved.


76

Property to set
tool tip text Tool tip text

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

 2006 Pearson Education, Inc. All rights reserved.


77

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

 2006 Pearson Education, Inc. All rights reserved.


78

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.

Fig. 13.35 | NumericUpDown properties and event.

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 13.36: interestCalculatorForm.cs 79
2 // Demonstrating the NumericUpDown control.
3 using System;
Outline
4 using System.Windows.Forms;
5
6 public partial class interestCalculatorForm : Form
7 { interestCalculator
8 // default constructor Form.cs
9 public interestCalculatorForm()
10 { (1 of 2)
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 Retrieve, convert, and assign
23 principalTextBox,
24 // retrieve user input InterestTextBox, and
25 principal = Convert.ToDecimal( principalTextBox.Text ); yearUpDown’s values
26 rate = Convert.ToDouble( interestTextBox.Text );
27 year = Convert.ToInt32( yearUpDown.Value );

 2006 Pearson Education,


Inc. All rights reserved.
28
80
29 // set output header
30 output = "Year\tAmount on Deposit\r\n"; Outline
31
32 // calculate amount after each year and append to output
33 for ( int yearCounter = 1; yearCounter <= year; yearCounter++ )
34 {
35 amount = principal * interestCalculator
36 ( ( decimal ) Math.Pow( ( 1 + rate / 100 ), yearCounter ) ); Form.cs
37 output += ( yearCounter + "\t" +
38 string.Format( "{0:C}", amount ) + "\r\n" );
39 } // end for
Calculate interest
(2 and
of 2)
40 format it as a String
41 displayTextBox.Text = output; // display result
42 } // end method calculateButton_Click
43 } // end class interestCalculatorForm Output results in
displayTextBox
Click to increase
number of years

NumericalUpDown
control

Click to decrease
number of years

 2006 Pearson Education,


Inc. All rights reserved.
81

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

 2006 Pearson Education, Inc. All rights reserved.


82

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.

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

 2006 Pearson Education, Inc. All rights reserved.


83

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.

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

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig 13.38: PainterForm.cs 84
2 // Using the mouse to draw on a Form.
3 using System;
Outline
4 using System.Drawing;
5 using System.Windows.Forms;
6
7 // creates a Form that is a drawing surface PainterForm.cs
8 public partial class PainterForm : Form
9 { (1 of 2)
10 bool shouldPaint = false; // determines whether to paint
11
12 // default constructor
Default instance variable to
13 public PainterForm()
14 {
false to identify that
15 InitializeComponent(); painting will not occur
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
Set shouldPaint to
22 shouldPaint = true;
23 } // end method PainterForm_MouseDown
true to identify that
24 painting will occur
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; Set shouldPaint to
30 } // end method PainterForm_MouseUp false to identify that
 2006 Pearson Education,
painting will not occur
Inc. All rights reserved.
31
85
32 // draw circle whenever mouse moves with its button held down
33 private void PainterForm_MouseMove( object sender, MouseEventArgs e ) Outline
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(); PainterForm.cs
39 graphics.FillEllipse(
40 new SolidBrush( Color.BlueViolet ), e.X, e.Y, 4, 4 );
41 graphics.Dispose(); (1 Form
Paint on the of 2) when
42 } // end if mouse is being pressed
43 } // end method PainterForm_MouseMove
44 } // end class PainterForm

 2006 Pearson Education,


Inc. All rights reserved.
86

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.

 2006 Pearson Education, Inc. All rights reserved.


87

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.

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

 2006 Pearson Education, Inc. All rights reserved.


88

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.

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

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 13.40: KeyDemoForm.cs 89
2 // Displaying information about the key the user pressed.
3 using System;
Outline
4 using System.Windows.Forms;
5
6 // Form to display key information when key is pressed
7 public partial class KeyDemoForm : Form KeyDemoForm.cs
8 {
9 // default constructor (1 of 3)
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
Property that returns the
ASCII character for the
key pressed

 2006 Pearson Education,


Inc. All rights reserved.
20 90
21 // display modifier keys, key code, key data and key value
22 private void KeyDemoForm_KeyDown( object sender, KeyEventArgs e )
Outline
23 {
Return the key code for the key as a
24 keyInfoLabel.Text =
25 "Alt: " + ( e.Alt ? "Yes" : "No" ) + '\n' +
value from the Keys enumerations
26 "Shift: " + ( e.Shift ? "Yes" : "No" ) + '\n' + KeyDemoForm.cs
27 "Ctrl: " + ( e.Control ? "Yes" : "No" ) + '\n' +
28 "KeyCode: " + e.KeyCode + '\n' +
Returns the key code for (2 of 3)
a key combined with
29 "KeyData: " + e.KeyData + '\n' +
30 "KeyValue: " + e.KeyValue;
modifier information as a Key value
31 } // end method KeyDemoForm_KeyDown
32 Returns key code as an int
33 // clear Labels when key released
34 private void KeyDemoForm_KeyUp( object sender, KeyEventArgs e )
35 {
36 charLabel.Text = "";
Reset labels
37 keyInfoLabel.Text = "";
38 } // end method KeyDemoForm_KeyUp
39 } // end class KeyDemoForm

 2006 Pearson Education,


Inc. All rights reserved.
91
Outline
(a) H pressed

KeyDemoForm.cs
(b) F12 pressed

(3 of 3)

(c) $ pressed

(d) Enter pressed

 2006 Pearson Education,


Inc. All rights reserved.

S-ar putea să vă placă și