History 476, Spring, 2011. The Sun Dialogs with the Inca The Sun Dialogs with the Inca.
T U T O R I A L 2009 Pearson Education, Inc. All rights reserved. 1 21 Typing Application...
-
Upload
joseph-sharp -
Category
Documents
-
view
212 -
download
0
Transcript of T U T O R I A L 2009 Pearson Education, Inc. All rights reserved. 1 21 Typing Application...
T U T O R I A L
2009 Pearson Education, Inc. All rights reserved.
1
21Typing Application
Introducing Keyboard Events, Menus, Dialogs and theDictionary Collection
2009 Pearson Education, Inc. All rights reserved.
2
Outline
21.1 Test-Driving the Typing Application
21.2 Analyzing the Typing Application
21.3 Keyboard Events
21.4 IsNot Operator
21.5 Menus
2009 Pearson Education, Inc. All rights reserved.
3
In this tutorial you will learn: ■ Handle keyboard events.■ Create menus for your Windows applications.■ Use dialogs to display messages.■ Use the ShowDialog method of the Font and
Color dialogs.■ Display the Font dialog to enable users to
choose fonts.
Objectives
2009 Pearson Education, Inc. All rights reserved.
4
In this tutorial you will learn: ■ Display the Color dialog to enable users to
choose colors.■ Use operator IsNot to compare references.■ Use a Dictionary to store pairs of keys and
values.■ Use LINQ to Objects to search a Form’s Controls collection.
Objectives
Application Requirements
2009 Pearson Education, Inc. All rights reserved.
5
21.1 Test-Driving the Typing Application
A high-school course teaches students how to type. The instructor would like to use a Windows application that allows students to watch what they are typing on the screen without looking at the keyboard. The application has to display a virtual keyboard that highlights any key the student presses on the real keyboard. This application must also contain menu commands for selecting the font style and color of the text displayed, clearing the text displayed and inverting the background and foreground colors of the display.
2009 Pearson Education, Inc. All rights reserved.
6
Test-Driving the Typing Application
■ Open the completed application and type a sentence into the TextBox (Fig. 21.1).
Figure 21.1 | Typing application with key pressed.
Virtual keyboard
Display menu
Highlighted key
2009 Pearson Education, Inc. All rights reserved.
7
Test-Driving the Typing Application (Cont.)
■ From the top menu, select Display > Text > Font... (Fig. 21.2).
Figure 21.2 | Selecting the Font... menu item.
Menu item
Submenu
2009 Pearson Education, Inc. All rights reserved.
8
Test-Driving the Typing Application (Cont.)
■ The Font dialog (Fig. 21.3) appears.
Figure 21.3 | Font dialog displayed when Display > Text > Font... is selected.
2009 Pearson Education, Inc. All rights reserved.
9
Test-Driving the Typing Application (Cont.)
■ Select Display > Text > Color... to display the Color dialog (Fig. 21.4).
■ This dialog allows you to choose the color of the text displayed.
Figure 21.4 | Color dialog displayed when Display > Text > Color... is selected.
2009 Pearson Education, Inc. All rights reserved.
10
Test-Driving the Typing Application (Cont.)
■ Select Display > Invert Colors (Fig. 21.5).
Figure 21.5 | Selecting the Invert Colors menu item.
2009 Pearson Education, Inc. All rights reserved.
11
Test-Driving the Typing Application (Cont.)
■ This option allows you to swap the background and foreground colors (Fig. 21.6).
Figure 21.6 | Output with colors inverted.
■ Select Display > Clear TextBox to remove all the text from the TextBox.
2009 Pearson Education, Inc. All rights reserved.
12
When the user presses a key:Highlight the corresponding Button on the GUI
When the user releases a key:Reset the corresponding Button’s background
color to the Button’s default background color
When the user selects the Color... menu item:Display the Color dialogUpdate the TextBox text’s color
21.2 Analyzing the Typing Application
2009 Pearson Education, Inc. All rights reserved.
13
When the user selects the Font... menu item:Display the Font dialogUpdate the TextBox text’s font
When the user selects the Clear TextBox menu item:
Clear the TextBox
When the user selects the Invert Colors menu item:
Swap the TextBox’s background and foreground colors
21.2 Analyzing the Typing Application
2009 Pearson Education, Inc. All rights reserved.
14
Action Control Event
Label the application’s controls promptLabel Application is run
outputTextBox KeyPress, KeyDown
Highlight the corresponding Button on the GUI keyboard Buttons
outputTextBox KeyUp
Reset the corresponding Button’s background
color to the Button’s default background color
keyboard Buttons
colorMenuItem Click
Display the Color dialog dialog
Update the TextBox text’s color outputTextBox
■ Use an ACE table to convert the pseudocode into Visual Basic (Fig. 21.7).
Figure 21.7 | ACE table for the Typing Application. (Part 1 of 2.)
Action/Control/Event (ACE) Table forthe Typing Application
2009 Pearson Education, Inc. All rights reserved.
15
Action Control Event
fontMenuItem Click
Display the Font dialog dialog
Update the TextBox text’s font outputTextBox
clearMenuItem Click
Clear the TextBox outputTextBox
invertMenuItem Click
Swap the TextBox’s background and
foreground colors
outputTextBox
Figure 21.7 | ACE table for the Typing Application. (Part 2 of 2.)
Action/Control/Event (ACE) Table forthe Typing Application (Cont.)
2009 Pearson Education, Inc. All rights reserved.
16
Coding the KeyDown Event Handler
■ Open the template application and add the following lines (Fig. 21.8) to your code.
Figure 21.8 | Determining whether the pressed key is a control key,function key or arrow key.
Determine whether the pressed key is a control key, function key
or arrow key
2009 Pearson Education, Inc. All rights reserved.
17
■ When a key is pressed, the KeyDown event (Fig. 21.9) is raised.
– The sender Object is the GUI component with the focus.
– The KeyEventArgs object e contains data for the event.
– The KeyCode property specifies which key was pressed.
■ The Keys enumeration represents keyboard keys using meaningful names.
■ The Char class’s IsControl method determines whether the pressed key is a control character.
Coding the KeyDown Event Handler (Cont.)
2009 Pearson Education, Inc. All rights reserved.
18
Figure 21.9 | Method IsFunctionOrArrowKey provided in the template.
Coding the KeyDown Event Handler (Cont.)
2009 Pearson Education, Inc. All rights reserved.
19
■ Visual Basic infers the type of variable from the result of the LINQ expression (lines 15–21 of Fig. 21.10).
Figure 21.10 | Using LINQ to locate the Button that matches the pressed key.
■ The TypeOf...Is expression determines whether currentControl is of the type Button.
Coding the KeyDown Event Handler (Cont.)
Using LINQ to Objects to query the Form’s Controls collection
and locate the Button that matches the pressed key
2009 Pearson Education, Inc. All rights reserved.
20
■ A Dictionary collection is used to map the KeyCode of the pressed key to the Text of a Button in the GUI.
– A Dictionary is a collection of key/value pairs.
– The template code for this application includes a predefined keyDictionary that maps various keys to their Buttons.
■ The Form’s Load event handler (Fig. 21.11) uses Dictionary method Add to insert key/value pairs.
Coding the KeyDown Event Handler (Cont.)
2009 Pearson Education, Inc. All rights reserved.
21
Figure 21.11 | Adding key/value pairs to the keyDictionary.
Coding the KeyDown Event Handler (Cont.)
Adding key/value pairs to the keyDictionary to represent the
function keys
Adding key/value pairs to the keyDictionary to represent the
control and arrow keys
2009 Pearson Education, Inc. All rights reserved.
22
■ The LINQ expression’s Where clause uses the ContainsKey method to check for the key’s String.
■ The CType operator converts the variable’s type (in this case, from Control to Button).
■ Line 21 (Fig. 21.12) determines whether the collection returned by the LINQ expression contains any elements.
Coding the KeyDown Event Handler (Cont.)
Figure 21.12 | Changing the color of the Button that corresponds to the pressed key.
If there is a Button that matches the pressed key, change the Button’s background color
2009 Pearson Education, Inc. All rights reserved.
23
■ Add the KeyPress event handler to outputTextBox (Fig. 21.13).
Figure 21.13 | Determining the Button that matches the pressed key.
Coding to the KeyPress Event Handler
Using LINQ to Objects to query the Form’s Controls collection
and locate the Button that matches the pressed key
■ Variable e referes to a KeyPressEventArgs object.
■ Property KeyChar represents the character on the key that was pressed.
■ ToUpper returns the String in uppercase.
2009 Pearson Education, Inc. All rights reserved.
24
■ If the KeyChar contains a space, the space bar was pressed and ChangeColor with spaceButton as an argument (Fig. 21.14).
Figure 21.14 | Changing the color of the Button that corresponds to the pressed key.
If the KeyChar is a space,change the background colorof the Button that represents
the space bar
Coding to the KeyPress Event Handler (Cont.)
If there is a Button that matches the pressed key, change the Button’s background color
2009 Pearson Education, Inc. All rights reserved.
25
■ Control keys, such as F1, do not raise the KeyPress event.
■ The KeyPress event cannot test for the modifier keys (Ctrl, Shift and Alt).
■ The KeyUp event is raised when a key is released, regardless of whether the key press is handled by the KeyPress or the KeyDown event handler.
Coding to the KeyPress Event Handler (Cont.)
2009 Pearson Education, Inc. All rights reserved.
26
Software Design Tip
Use the KeyPress event handler for letter and number key events. Use the KeyDown event handler for modifier and control key events.
2009 Pearson Education, Inc. All rights reserved.
27
■ To generate KeyUp, KeyDown or KeyPress event handlers for controls (Fig. 21.15):
Creating the KeyUp Event Handler
Figure 21.15 | Generating the KeyUp event handler.
Class Name ComboBox
Method Name ComboBox drop-down list
2009 Pearson Education, Inc. All rights reserved.
28
■ The KeyUp event handler (Fig. 21.16) executes whenever a key is released/
■ Change the color of the released Button back to that Button’s default color.
Figure 21.16 | Resetting a Button’s color when its key is released.
Resetting a Button’s colorafter a key is released
Creating the KeyUp Event Handler (Cont.)
2009 Pearson Education, Inc. All rights reserved.
29
■ The IsNot operator can compare a reference type variable’s value to the value Nothing.
– The condition evaluates to True if the variable refers to an object.
■ You can also use IsNot to compare two reference type variables to determine whether or not they refer to the same object.
21.4 IsNot Operator
2009 Pearson Education, Inc. All rights reserved.
30
Figure 21.17 | IsNot operator inside the ResetColor method
21.4 IsNot Operator (Cont.)
■ The ResetColor method (Fig 21.17) restores the color of a Button when the corresponding key is released.
2009 Pearson Education, Inc. All rights reserved.
31
■ Menus allow you to group related commands for Windows applications.
■ Although most menus and commands vary among applications, some—such as Open and Save—are common to many applications.
■ Menus are an important part of GUIs because they organize commands without cluttering the GUI.
21.5 Menus
2009 Pearson Education, Inc. All rights reserved.
32
■ Add a MenuStrip from the Menus &Toolbars tab of the Toolbox.
■ A box appears on the top of your Form representing a menu item (Fig. 21.18).
Creating a Menu
Figure 21.18 | MenuStrip control added to the Typing application.
MenuStrip control inthe component tray
ToolStripMenuItem field
2009 Pearson Education, Inc. All rights reserved.
33
■ Click the icon in the component tray or the menu on the Form to enter Menu Designer.
■ Change the Name property of the MenuStrip control to menuBar.
■ Type &Display into the Type Here box and press Enter.
■ Change the Name of the ToolstripMenuItem to displayMenuItem.
■ Two more fields appear (Fig. 21.19).
Creating a Menu (Cont.)
2009 Pearson Education, Inc. All rights reserved.
34
Figure 21.19 | Creating the Display menu.
Creating a Menu (Cont.)
Menu item
2009 Pearson Education, Inc. All rights reserved.
35
Good Programming Practice
We suggest appending the MenuItem suffix to ToolStripMenuItem controls.
2009 Pearson Education, Inc. All rights reserved.
36
GUI Design Tip
Use book-title capitalization in menu-item text.
2009 Pearson Education, Inc. All rights reserved.
37
■ In the box below the Display menu, type &Clear TextBox and name this menu item clearMenuItem (Fig. 21.20).
■ Entering text in the right box turns the menu item on the left into a submenu.
■ Type &Invert Colors below the last MenuItem and name this invertMenuItem.
Creating a Menu (Cont.)
2009 Pearson Education, Inc. All rights reserved.
38
Figure 21.20 | Adding items to the menu.
Creating a Menu (Cont.)
Submenu
Submenu item
2009 Pearson Education, Inc. All rights reserved.
39
■ Click the small arrow on the right side of the Type Here box.
– Select Separator from the drop-down list (Fig. 21.21).
Creating a Menu (Cont.)
Click down arrow to display drop-down
list
Select Separator to insert a separator bar
Figure 21.21 | Adding a separator bar to group menu items.
2009 Pearson Education, Inc. All rights reserved.
40
GUI Design Tip
Use separator bars in a menu to group related menu items.
2009 Pearson Education, Inc. All rights reserved.
41
■ In the box under the separator bar, type &Text and name this textMenuItem.
– Insert &Color... and &Font... as menu items in the Text submenu.
– Name them colorMenuItem and fontMenuItem, respectively (Fig. 21.22).
Creating a Menu (Cont.)
2009 Pearson Education, Inc. All rights reserved.
42
Figure 21.22 | Adding a submenu to a menu item.
Creating a Menu (Cont.)
Separator bar
2009 Pearson Education, Inc. All rights reserved.
43
GUI Design Tip
If clicking a menu item opens a dialog, an ellipsis (…) should follow the menu item’s text.
2009 Pearson Education, Inc. All rights reserved.
44
■ Double click the Font... menu item that you created to generate its Click event handler (Fig. 21.23).
Figure 21.23 | Declarations for the FontDialog and its DialogResult.
Declaration for theFontDialog and its result
Coding the Font... Menu Item’sClick Event Handler
2009 Pearson Education, Inc. All rights reserved.
45
■ These lines (Fig. 21.24) call the ShowDialog method to display the Font dialog to the user.
■ The return value of ShowDialog is assigned to variable result.
Figure 21.24 | Opening the Font dialog.
Showing the dialog and assigning the result
Coding the Font... Menu Item’sClick Event Handler (Cont.)
2009 Pearson Education, Inc. All rights reserved.
46
■ These lines (Fig. 21.25) determine whether the user has clicked the Font dialog’s Cancel Button.
– The value stored in result is compared to the enumeration value DialogResult.Cancel.
– If the user clicks the Cancel Button, no action takes place and the method exits.
Coding the Font... Menu Item’sClick Event Handler (Cont.)
Take no action if user cancels
Figure 21.25 | Exit the event handler if the user clicks Cancel.
2009 Pearson Education, Inc. All rights reserved.
47
■ Lines 128–129 of Fig. 21.26 give the text the style that the user has selected from the FontDialog.
Figure 21.26 | Changing the display font.
Assigning the new font value
Coding the Font... Menu Item’sClick Event Handler (Cont.)
2009 Pearson Education, Inc. All rights reserved.
48
■ Double click the Color... menu item to generate its Click event handler (Fig. 21.27).
Figure 21.27 | Declarations for the Color dialog and its DialogResult.
Declarations for the ColorDialog and its result
Coding the Color... Menu Item’sClick Event Handler
2009 Pearson Education, Inc. All rights reserved.
49
■ To display the Color dialog as in the completed application, the FullOpen option must be set to True(line 139 of Fig. 21.28).
Figure 21.28 | Displaying the Color dialog.
Displaying the ColorDialog with a complete color selection
Coding the Color... Menu Item’sClick Event Handler (Cont.)
2009 Pearson Education, Inc. All rights reserved.
50
■ This If...Then statement (Fig. 21.29) prevents the color from being changed if the user clicks Cancel.
Figure 21.29 | Changing the display text’s color.
Take no action if user cancels
Coding the Color... Menu Item’sClick Event Handler (Cont.)
Change text color inthe TextBox
2009 Pearson Education, Inc. All rights reserved.
51
■ Double click the Clear TextBox menu item to generate its Click event (Fig. 21.30).
Figure 21.30 | Calling the Clear method of class TextBox to erase the text.
Clearing the TextBox
2009 Pearson Education, Inc. All rights reserved.
52
■ Double click the Invert Colors menu item in Design view to create its Click event handler (Fig. 21.31).
Figure 21.31 | Empty event handler for Invert Color menu item.
Inverting Colors
2009 Pearson Education, Inc. All rights reserved.
53
■ To swap colors, you must use a temporary Color variable to hold one of the colors that you want to swap (Fig. 21.32).
Figure 21.32 | Swapping the background and foreground colors.
Inverting Colors (Cont.)
Using a temporary variableto swap color values
2009 Pearson Education, Inc. All rights reserved.
54
1 Public Class TypingForm
2 Private lastButton As Button ' reference to last Button pressed
3 Private keyDictionary As New Dictionary(Of String, String)
4
5 ' handles Form's KeyDown Event
6 Private Sub outputTextBox_KeyDown(ByVal sender As Object, _
7 ByVal e As System.Windows.Forms.KeyEventArgs) _
8 Handles outputTextBox.KeyDown
9
10 If Char.IsControl(Convert.ToChar(e.KeyCode)) OrElse _
11 IsFunctionOrArrowKey(e.KeyCode) Then
12
■ Figure 21.33 presents the source codefor the Typing application.
Outline
(1 of 10 )
Converting a KeyCode to a Char using Convert.ToChar
Instance variable to store which Button the user pressed
2009 Pearson Education, Inc. All rights reserved.
55
13 ' locate the Button representing the pressed key with LINQ
14 Dim pressed = _
15 From currentControl In Me.Controls _
16 Where TypeOf currentControl Is Button AndAlso _
17 keyDictionary.ContainsKey( _
18 e.KeyCode.ToString()) AndAlso _
19 keyDictionary(e.KeyCode.ToString()) = _
20 CType(currentControl, Button).Text _
21 Select currentControl
22
23 If pressed.Count > 0 Then
24 ChangeColor(CType(pressed.First, Button))
25 End If
26 End If
27 End Sub ' OutputTextBox_KeyDown
28
29 ' handles Form KeyPress Event
30 Private Sub outputTextBox_KeyPress(ByVal sender As Object, _
31 ByVal e As System.Windows.Forms.KeyPressEventArgs) _
32 Handles outputTextBox.KeyPress
Outline
(2 of 10 )
Determining if the key pressed is a control character
Converting a Control to a Button using CType
Determining if the Dictionary contains a key matching the KeyCode’s String representation
Determining a Control’s type using TypeOf
2009 Pearson Education, Inc. All rights reserved.
56
33
34 ' locate the Button matching the pressed key with LINQ
35 Dim pressed = _
36 From currentControl In Me.Controls _
37 Where TypeOf currentControl Is Button AndAlso _
38 e.KeyChar.ToString().ToUpper() = _
39 CType(currentControl, Button).Text _
40 Select currentControl
41
42 If e.KeyChar = " " Then ' if user pressed spacebar
43 ChangeColor(spaceButton)
44 Else
45 If pressed.Count > 0 Then
46 ChangeColor(CType(pressed.First, Button))
47 End If
48 End If
49 End Sub ' outputTextBox_KeyPress
50
Outline
(3 of 10 )
2009 Pearson Education, Inc. All rights reserved.
57
51 ' handles the TextBox's KeyUp event
52 Private Sub outputTextBox_KeyUp(ByVal sender As Object, _
53 ByVal e As System.Windows.Forms.KeyEventArgs) _
54 Handles outputTextBox.KeyUp
55
56 ResetColor()
57 End Sub ' outputTextBox_KeyUp
58
59 ' highlight Button passed as argument
60 Private Sub ChangeColor(ByVal buttonPassed As Button)
61 ResetColor()
62 buttonPassed.BackColor = Color.Yellow
63 lastButton = buttonPassed ' save Button to reset color later
64 End Sub ' ChangeColor
65
66 ' changes lastButton's color if it refers to a Button
67 Private Sub ResetColor()
68 If lastButton IsNot Nothing Then
69 lastButton.BackColor = SystemColors.Control
70 End If
71 End Sub ' ResetColor
Outline
(4 of 10 )
Using the IsNot operator to determine whether lastButton refers to Nothing
2009 Pearson Education, Inc. All rights reserved.
58
72
73 ' configure keyDictionary for use with control keys;
74 ' key is the key code's string value; value is the Button label
75 Private Sub TypingForm_Load(ByVal sender As System.Object, _
76 ByVal e As System.EventArgs) Handles MyBase.Load
77
78 ' add function keys
79 For i As Integer = 1 To 12
80 keyDictionary.Add("F" & i, "F" & i)
81 Next
82
Outline
(5 of 10 )
2009 Pearson Education, Inc. All rights reserved.
59
83 ' add other control keys
84 keyDictionary.Add("Back", "Backspace")
85 keyDictionary.Add("Return", "Enter")
86 keyDictionary.Add("ControlKey", "Ctrl")
87 keyDictionary.Add("Menu", "Alt")
88 keyDictionary.Add("Capital", "Caps Lock")
89 keyDictionary.Add("ShiftKey", "Shift")
90 keyDictionary.Add("Tab", "Tab")
91 keyDictionary.Add("Up", "^")
92 keyDictionary.Add("Down", "v")
93 keyDictionary.Add("Left", "<")
94 keyDictionary.Add("Right", ">")
95 End Sub ' TypingForm_Load
96
97 ' determine whether pressed key is a function or arrow key
98 Function IsFunctionOrArrowKey(ByVal code As Keys) As Boolean
99 Dim result As Boolean
100
Outline
(6 of 10 )
Adding items to a Dictionary
2009 Pearson Education, Inc. All rights reserved.
60
101 Select Case code
102 Case Keys.F1 To Keys.F12
103 result = True
104 Case Keys.Up, Keys.Down, Keys.Left, Keys.Right
105 result = True
106 Case Else
107 result = False ' not a match
108 End Select
109
110 Return result
111 End Function ' isFunctionOrArrowKey
112
113 ' handles Font menu item's Click event
114 Private Sub fontMenuItem_Click(ByVal sender As System.Object, _
115 ByVal e As System.EventArgs) Handles fontMenuItem.Click
116
117 Dim dialog As FontDialog = New FontDialog()
118 Dim result As DialogResult ' stores Button clicked
119
Outline
(7 of 10 )
Create FontDialog and DialogResult variables
2009 Pearson Education, Inc. All rights reserved.
61
120 ' show dialog and get result
121 result = dialog.ShowDialog()
122
123 ' do nothing if user clicked dialog's Cancel Button
124 If result = System.Windows.Forms.DialogResult.Cancel Then
125 Return
126 End If
127
128 ' assign new font value to TextBox
129 outputTextBox.Font = dialog.Font
130 End Sub ' fontMenuItem_Click
131
132 ' handles Color menu item's Click event
133 Private Sub colorMenuItem_Click(ByVal sender As System.Object, _
134 ByVal e As System.EventArgs) Handles colorMenuItem.Click
135
136 Dim dialog As ColorDialog = New ColorDialog()
137 Dim result As DialogResult ' stores Button clicked
138
Outline
(8 of 10 )
Display dialog and get Button clicked to exit the dialog
Change the text’s font to the value the user selected
2009 Pearson Education, Inc. All rights reserved.
62
139 dialog.FullOpen = True ' show all colors
140 result = dialog.ShowDialog()
141
142 ' do nothing if user clicked dialog's Cancel Button
143 If result = System.Windows.Forms.DialogResult.Cancel Then
144 Return
145 End If
146
147 ' assign new color value to TextBox
148 outputTextBox.ForeColor = dialog.Color
149 End Sub ' colorMenuItem_Click
150
151 ' handles Clear TextBox menu item's Click Event
152 Private Sub clearMenuItem_Click(ByVal sender As System.Object, _
153 ByVal e As System.EventArgs) Handles clearMenuItem.Click
154
155 outputTextBox.Clear() ' clear TextBox
156 End Sub ' clearMenuItem_Click
Outline
(9 of 10 )
Show all color options in the dialog
Display dialog and get Button clicked to exit the dialog
Change the text’s color to the value the user selected
2009 Pearson Education, Inc. All rights reserved.
63
157
158 ' handles Invert Colors menu item's Click Event
159 Private Sub invertMenuItem_Click(ByVal sender As System.Object, _
160 ByVal e As System.EventArgs) Handles invertMenuItem.Click
161
162 Dim temporaryColor As Color ' temporary Color value
163
164 temporaryColor = outputTextBox.BackColor
165 outputTextBox.BackColor = outputTextBox.ForeColor
166 outputTextBox.ForeColor = temporaryColor
167 End Sub ' invertMenuItem_Click
168 End Class ' Typing
Outline
(10 of 10 )
Swap text color and background color