Click here to load reader

Graphical User Interfaces with Windows Forms

Embed Size (px)

DESCRIPTION

14. Graphical User Interfaces with Windows Forms. . . .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. Apple Computer, Inc. - PowerPoint PPT Presentation

Citation preview

1*
*
*
. . .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.
Apple Computer, Inc.
Horace Walpole
*
Design principles of graphical user interfaces (GUIs).
How to create graphical user interfaces.
*
*
How to create and manipulate Button, Label, RadioButton, CheckBox, TextBox, GroupBox, Panel, PictureBox, ToolTip, NumericUpDown, MonthCalendar, LinkLabel, ListBox, CheckedListBox, ComboBox, TreeView, and ListView controls.
To create menus, tabbed windows and multiple document interface (MDI) programs.
How to create custom controls.
*
*
14.6   GroupBoxes and Panels
14.7   CheckBoxes and RadioButtons
*
*
14.24   Visual Inheritance
14.25   User-Defined Controls
*
14.1  Introduction
A graphical user interface (GUI) allows a user to interact visually with a program.
Figure 14.1 shows a Visual Basic 2008 Express Edition window’s GUI controls.
Fig. 14.1 | GUI controls in an Internet Explorer window.
Menu
*
Look-and-Feel Observation 14.1
Consistent user interfaces enable a user to learn new applications faster because the applications have the same look-and-feel.
14.1  Introduction (Cont.)
*
Fig. 14.2 | Some basic GUI controls.
*
TextBox
Button
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.
Panel
A container in which controls can be placed and organized.
NumericUpDown
Enables the user to select from a range of numeric input values.
2009 Pearson Education, Inc. All rights reserved.
*
Windows Forms are used to create the GUIs for programs.
A Form can be a dialog, a window or an MDI window.
*
*
Figure 14.3 displays the Visual Basic Toolbox.
To add a control or component to a Form, select and drag it onto the Form.
Categories that
*
*
14.2 Windows Forms (Cont.)
The active window is the frontmost and has a highlighted title bar. The active window is said to “have the focus.”
*
*
14.2  Windows Forms (Cont.)
*
Description
AutoScroll
CancelButton
Button that is clicked when the Escape key is pressed.
FormBorderStyle
Font
Text
*
14.2  Windows Forms (Cont.)
*
Description
Hide
Hides a Form, but does not destroy the Form or release its resources.
Show
2009 Pearson Education, Inc. All rights reserved.
*
an event drives the program to perform a task.
A method that performs a task in response to
an event is called an event handler.
*
*
a Button which displays a MessageBox.
Outline
SimpleEventExampleForm.vb
clickMeButton’s Click event handler.
*
3 Public Class SimpleEventExampleForm
7
*
Create a Windows Forms Application and add a Button.
In the Properties window, set the (Name) property to ClickMeButton and the Text property to Click Me.
Create an event handler by double clicking the Button.
Private Sub clickMeButton_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles clickMeButton.Click
End Sub
*
14.3 Event Handling (cont.)
Software Engineering Observation 14.1
Event handlers do not return values—they are designed to execute code based on an action and return control to the main program.
Good Programming Practice 14.1
Use the event-handler naming convention controlName_eventName so that your method names
*
*
MessageBox.Show("Button was clicked.")
*
14.3.2 Another Look at the Visual Studio Generated Code
Visual Studio generates the code that creates and initializes the GUI you build in the GUI design window (Figs. 14.6 and 14.7).
*
*
14.3 Event Handling (Cont.)
*
*
14.3 Event Handling (Cont.)
• The auto-generated code that defines the GUI is actually part of the Form’s class.
• The Partial modifier allows this class to be split among multiple files.
Error-Prevention Tip 14.1
*
*
14.3.3 Delegates and the Event-Handling Mechanism
• Event handlers are connected to a control’s events via delegates.
• The delegate for a Button’s Click event is of type EventHandler and is declared as follows:
Public Delegate Sub EventHandler(sender
As Object, e As EventArgs)
• The Handles clause “registers” your event handler as the method to call in response to the event.
Handles controlName.eventName
*
14.3.4 Other Ways to Create Event Handlers
Use the Class Name and Method Name ComboBoxes to select events for that control (Fig. 14.8).
*
*
• You can create additional event handlers through the Properties window.
• This can be used to have several events call the same method.
• Click the Events icon, then double click an event’s name (Fig. 14.9).
Fig. 14.7 | Viewing events for a Button control in the Properties window.
Events icon
Selected event
Properties icon
*
14.3 Event Handling (Cont.)
14.3.5 Locating Event Information
• Select Help > Index. In the window that appears, select .NET Framework in the Filtered by drop-down list and enter the name of the control’s class in the Index window.
*
*
*
*
• Click the name of an event to view its description
and examples of its use (Fig. 14.11).
Event usage
Event name
*
*
14.4  Control Properties and Layout
*
Description
BackgroundImage
Enabled
Focused
Font
ForeColor
The control’s foreground color. This usually determines text color.
TabIndex
TabStop
If True, then a user can give focus to this control via the Tab key.
2009 Pearson Education, Inc. All rights reserved.
*
14.4  Control Properties and Layout (Cont.)
*
Description
Visible
Common Methods
Show
2009 Pearson Education, Inc. All rights reserved.
*
• The Focus method transfers the focus to a control.
• When you press the Tab key, controls receive the focus in the order specified by their TabIndex property.
*
*
• Anchoring causes controls to remain at a fixed distance from the sides of the container.
• Set the Anchor property as shown in Fig. 14.13.
14.4 Control Properties and Layout (cont.)
Fig. 14.13 | Manipulating the Anchor property of a control.
Anchoring window
side(s) to which the control is anchored;
use mouse clicks to select or deselect a bar
*
*
Execute the application and enlarge the Form (Fig. 14.14).
Fig. 14.14 | Anchoring demonstration.
Before resizing
After resizing
*
14.4 Control Properties and Layout (Cont.)
Docking allows a control to span an entire side or fill its parent container.
Forms have a Padding property that specifies the docked item’s distance from the edge.
Fig. 14.15 | Docking a Button to the top of a Form.
Before resizing
After resizing
*
*
Fig. 14.16 | Control layout properties.
Look-and-Feel Observation 14.2
*
Description
Anchor
Causes a control to remain at a fixed distance from the side(s).
Dock
Allows a control to span one side or fill its container.
Padding
Sets the space between a container’s edges and docked controls.
Location
Specifies the location (as a set of coordinates) of the control.
Size
Specifies the size of the control in pixels as a Size object.
MinimumSize,
MaximumSize
2009 Pearson Education, Inc. All rights reserved.
*
14.4  Control Properties and Layout (Cont.)
Snap lines appear to help you position a control with respect to other controls (Fig. 14.17).
When selecting a control, the Format menu contains several options for modifying your GUI’s layout.
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. 14.17 | Snap lines in Visual Studio 2008.
*
*
*
Text
TextAlign
The alignment of the Label’s text on the control—horizontally (left, center or right) and vertically (top, middle or bottom).
2009 Pearson Education, Inc. All rights reserved.
*
Fig. 14.19 | TextBox properties and an event.
*
Description
AcceptsReturn
If True in a multiline TextBox, pressing Enter creates a new line.
Multiline
UseSystem- PasswordChar
ReadOnly
ScrollBars
Text
Common Event
2009 Pearson Education, Inc. All rights reserved.
*
Fig. 14.20 | Button properties and an event.
Look-and-Feel Observation 14.3
*
Description
FlatStyle
Common Event
*
user clicks the Show Me Button, the text typed in
the password TextBox is displayed in a Label.
Make inputPasswordTextBox a password
TextBox by setting UseSystemPasswordChar
Obtaining the input text and displaying the text in displayPasswordLabel.
*
3 ' the hidden text in a password TextBox.
4 Public Class LabelTextBoxButtonTestForm
6 Private Sub displayPasswordButton_Click( _
8 Handles displayPasswordButton.Click
10 displayPasswordLabel.Text = inputPasswordTextBox.Text
*
( 2 of 2 )
*
*
GroupBoxes and Panels arrange controls on a GUI.
GroupBoxes can display a caption and do not include scrollbars, whereas Panels can include scrollbars and do not include a caption.
Fig. 14.22 | GroupBox properties.
Text
*
Fig. 14.23 | Panel properties.
GroupBoxes for more complex layouts.
*
Description
AutoScroll
Indicates whether scrollbars appear when the Panel is too small to display all of its controls.
BorderStyle
Controls
2009 Pearson Education, Inc. All rights reserved.
*
Look-and-Feel Observation 14.5
*
*
14.6 GroupBoxes and Panels (Cont.)
To create a GroupBox, drag its icon from the Toolbox onto the Form. Then drag new controls from the Toolbox into the GroupBox (Fig. 14.24).
Panel
*
*
Fig. 14.25 | Using GroupBoxes and Panels to
arrange Buttons. (Part 1 of 2.)
*
3 Public Class GroupBoxPanelExampleForm
7 messageLabel.Text = "Hi pressed" ' change text in Label
8 End Sub ' hiButton_Click
13 messageLabel.Text = "Bye pressed" ' change text in Label
14 End Sub ' byeButton_Click
19 messageLabel.Text = "Far left pressed" ' change text in Label
20 End Sub ' leftButton_Click
*
arrange Buttons. (Part 2 of 2.)
*
25 messageLabel.Text = "Far right pressed" ' change text in Label
26 End Sub ' rightButton_Click
27 End Class ' GroupBoxPanelExampleForm
*
14.7  CheckBoxes and RadioButtons
Visual Basic has two types of state buttons that can be in the on/off or true/false states—CheckBoxes and RadioButtons.
Any number of CheckBoxes can be selected at a time.
Fig. 14.26 | CheckBox properties and events.
*
CheckState
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.
CheckStateChanged
2009 Pearson Education, Inc. All rights reserved.
*
*
3 Public Class CheckBoxTestForm
6 Private Sub boldCheckBox_CheckedChanged( _
8 Handles boldCheckBox.CheckedChanged
16 Private Sub italicCheckBox_CheckedChanged( _
18 Handles italicCheckBox.CheckedChanged
*
d) Italic font style
*
*
14.7  CheckBoxes and RadioButtons (Cont.)
RadioButtons are used to represent a set of mutually exclusive options.
To separate RadioButtons into groups, use separate GroupBoxes or Panels.
Fig. 14.28 | RadioButton properties and an event.
*
Description
Text
Common Event
2009 Pearson Education, Inc. All rights reserved.
*
option in a group.
Use CheckBoxes when the user should be able to choose
multiple options (or no options at all) in a group.
Software Engineering Observation 14.2
Forms, GroupBoxes and Panels act as logical groups for RadioButtons. The RadioButtons within each group are mutually exclusive to each other, but not to those in different logical groups.
14.7  CheckBoxes and RadioButtons (Cont.)
*
*
Outline
RadioButtonsTest
Form.vb
( 1 of 11 )
To store the user’s choices, we create and initialize variables iconType and buttonType.
When a RadioButton is checked, its event handler sets buttonType to the appropriate value.
Fig. 14.29 | Using RadioButtons to set message-window
options. (Part 1 of 11.)
*
3 Public Class RadioButtonsTestForm
4 ' create variables that store the user's choice of options
5 Private iconType As MessageBoxIcon
6 Private buttonType As MessageBoxButtons
7
9 Private Sub okRadioButton_CheckedChanged( _
11 Handles okRadioButton.CheckedChanged
12 buttonType = MessageBoxButtons.OK
16 Private Sub okCancelRadioButton_CheckedChanged( _
18 Handles okCancelRadioButton.CheckedChanged
19 buttonType = MessageBoxButtons.OKCancel
*
options. (Part 2 of 11.)
*
23 Private Sub abortRetryIgnoreRadioButton_CheckedChanged( _
25 Handles abortRetryIgnoreRadioButton.CheckedChanged
26 buttonType = MessageBoxButtons.AbortRetryIgnore
30 Private Sub yesNoCancelRadioButton_CheckedChanged( _
32 Handles yesNoCancelRadioButton.CheckedChanged
33 buttonType = MessageBoxButtons.YesNoCancel
*
options. (Part 3 of 11.)
*
37 Private Sub yesNoRadioButton_CheckedChanged( _
39 Handles yesNoRadioButton.CheckedChanged
40 buttonType = MessageBoxButtons.YesNo
44 Private Sub retryCancelRadioButton_CheckedChanged( _
46 Handles retryCancelRadioButton.CheckedChanged
47 buttonType = MessageBoxButtons.RetryCancel
*
options. (Part 4 of 11.)
*
51 Private Sub asteriskRadioButton_CheckedChanged( _
53 Handles asteriskRadioButton.CheckedChanged
54 iconType = MessageBoxIcon.Asterisk
58 Private Sub errorRadioButton_CheckedChanged( _
60 Handles errorRadioButton.CheckedChanged
61 iconType = MessageBoxIcon.Error
*
options. (Part 5 of 11.)
*
65 Private Sub exclamationRadioButton_CheckedChanged( _
67 Handles exclamationRadioButton.CheckedChanged
68 iconType = MessageBoxIcon.Exclamation
72 Private Sub handRadioButton_CheckedChanged( _
74 Handles handRadioButton.CheckedChanged
75 iconType = MessageBoxIcon.Hand
*
options. (Part 6 of 11.)
*
79 Private Sub informationRadioButton_CheckedChanged( _
81 Handles informationRadioButton.CheckedChanged
82 iconType = MessageBoxIcon.Information
86 Private Sub questionRadioButton_CheckedChanged( _
88 Handles questionRadioButton.CheckedChanged
89 iconType = MessageBoxIcon.Question
*
options. (Part 7 of 11.)
*
93 Private Sub stopRadioButton_CheckedChanged( _
95 Handles stopRadioButton.CheckedChanged
96 iconType = MessageBoxIcon.Stop
100 Private Sub warningRadioButton_CheckedChanged( _
102 Handles warningRadioButton.CheckedChanged
103 iconType = MessageBoxIcon.Warning
*
Fig. 14.29 | Using RadioButtons to set message-window
options. (Part 8 of 11.)
*
109 ' display MessageBox and store
110 ' the value of the Button that was pressed
111 Dim result As DialogResult = MessageBox.Show( _
112 "This is your custom MessageBox.", _
113 "Custom MessageBox", buttonType, iconType, 0, 0)
114
*
options. (Part 9 of 11.)
*
115 ' check to see which Button was pressed in the MessageBox
116 ' change text displayed accordingly
117 Select Case result
120 Case DialogResult.Cancel
122 Case DialogResult.Abort
124 Case DialogResult.Retry
126 Case DialogResult.Ignore
128 Case DialogResult.Yes
130 Case DialogResult.No
132 End Select
*
options. (Part 10 of 11.)
*
*
options. (Part 11 of 11.)
*
*
*
Description
SizeMode
Common Event
*
Setting the Image property of the PictureBox to the resource.
Outline
PictureBoxTest
Form.vb
( 1 of 2 )
*
3 Imports System.IO
8
10 Private Sub nextButton_Click(ByVal sender As System.Object, _
11 ByVal e As System.EventArgs) Handles nextButton.Click
12
13 imageNum = (imageNum + 1) Mod 3 ' imageNum cycles from 0 to 2
14
16 Dim pictureResource = My.Resources.ResourceManager.GetObject( _
17 String.Format("image{0}", imageNum))
19 ' convert pictureResource to image type and load into PictureBox
20 imagePictureBox.Image = CType(pictureResource, Image)
21 End Sub ' nextButton_Click
22 End Class ' PictureBoxTestForm
*
( 2 of 2 )
*
*
14.9  ToolTips
Many programs use tool tips to remind users of each control’s purpose.
Fig. 14.32 | ToolTip properties and an event.
*
Description
AutoPopDelay
The amount of time (in milliseconds) that the tool tip appears.
InitialDelay
The amount of time that a mouse must hover over a control before a tool tip appears.
ReshowDelay
The amount of time between two different tool tips appearing.
Common Event
*
in the component tray—the gray region below the
Form in Design mode.
*
3 Public Class ToolTipDemonstrationForm
5 End Class ' ToolTipDemonstrationForm
*
ToolTip in
component tray
*
Property to set
tool tip text
Tool tip text
*
14.9  NumericUpDown Control
The NumericUpDown control restricts a user’s input choices to a specific range of numeric values.
Fig. 14.36 | NumericUpDown properties and an event.
*
Description
Increment
Specifies by how much the current number changes when the user clicks the up and down arrows.
Maximum
Minimum
UpDownAlign
Value
Common Event
ValueChanged
This event is raised when the value in the control is changed.
2009 Pearson Education, Inc. All rights reserved.
*
for a GUI that calculates interest rate.
Retrieving the value from the NumericUpDown control.
Outline
NumericUpDown
TestForm.vb
*
3 Public Class NumericUpDownTestForm
9 Dim rate As Double ' store interest rate
10 Dim year As Integer ' store number of years
11 Dim amount As Decimal ' store amount
12
*
*
20 vbNewLine
22 ' calculate amount after each year and append to output
23 For yearCounter As Integer = 1 To year
24 amount = principal * Convert.ToDecimal( _
26 displayTextBox.Text &= (yearCounter & vbTab & _
28 Next
*
*
*
14.10  NumericUpDown Control (Cont.)
We set the NumericUpDown’s ReadOnly property to True to indicate that the user cannot type a number into the control to make a selection.
*
*
14.11  Mouse-Event Handling
*
*
14.9  NumericUpDown Control (Cont.)
*
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 TypeMouseEventArgs
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 within the control’s boundaries.
2009 Pearson Education, Inc. All rights reserved.
*
14.9  NumericUpDown Control (Cont.)
*
Class MouseEventArgs Properties
Button
Specifies which mouse button was pressed (Left, Right, Middle or none).
Clicks
X
Y
2009 Pearson Education, Inc. All rights reserved.
*
When the user clicks drags the mouse in this program (Fig. 14.39), small circles appear at its position.
Handles a mouse button click.
Handles a mouse button release.
Outline
PaintForm.vb
( 1 of 2 )
*
3 Public Class PaintForm
4 Private shouldPaint As Boolean = False ' determines whether to paint
5
7 Private Sub PaintForm_MouseDown(ByVal sender As System.Object, _
8 ByVal e As MouseEventArgs) Handles MyBase.MouseDown
9 shouldPaint = True
13 Private Sub PaintForm_MouseUp(ByVal sender As System.Object, _
14 ByVal e As MouseEventArgs) Handles MyBase.MouseUp
15 shouldPaint = False
*
The program draws on a MouseMove only if shouldPaint is True.
Outline
PaintForm.vb
( 2 of 2 )
*
18 ' draw circle whenever mouse moves with its button held down
19 Private Sub Paint_MouseMove(ByVal sender As System.Object, _
20 ByVal e As MouseEventArgs) Handles MyBase.MouseMove
21 ' check if mouse button is being pressed
22 If (shouldPaint) Then
23 ' draw a circle where the mouse pointer is present
24 Dim g As Graphics = CreateGraphics()
25 g.FillEllipse( _
27 g.Dispose()
*
14.12  Keyboard-Event Handling
*
Key Events with Event Arguments of Type KeyEventArgs
KeyDown
KeyUp
Key Event with Event Argument of Type KeyPressEventArgs
KeyPress
Class KeyPressEventArgs Properties
Handled
*
14.12  Keyboard-Event Handling (Cont.)
*
Class KeyEventArgs Properties
Control
Shift
Handled
KeyCode
Returns the key code for the key as a value from the Keys enumeration.
KeyData
Returns the key code for a key combined with modifier information as a Keys value.
KeyValue
Returns the key code as an int, rather than as a value from the Keys enumeration.
Modifiers
Returns a Keys value indicating any pressed modifier keys (Alt, Ctrl and Shift).
2009 Pearson Education, Inc. All rights reserved.
*
*
3 Public Class KeyDemoForm
8
10 End Sub ' KeyDemoForm_KeyPress
11
12 ' display modifier keys, key code, key data and key value
13 Private Sub KeyDemoForm_KeyDown(ByVal sender As System.Object, _
14 ByVal e As KeyEventArgs) Handles MyBase.KeyDown
15
17 keyInfoLabel.Text = "Alt: Yes" & vbNewLine
18 Else ' key is not Alt
19 keyInfoLabel.Text = "Alt: No" & vbNewLine
20 End If
*
Responding to control keys.
*
23 keyInfoLabel.Text &= "Shift: Yes" & vbNewLine
24 Else ' key is not Shift
25 keyInfoLabel.Text &= "Shift: No" & vbNewLine
26 End If
29 keyInfoLabel.Text &= "Control: Yes" & vbNewLine
30 Else ' key is not Control
31 keyInfoLabel.Text &= "Control: No" & vbNewLine
32 End If
35 keyInfoLabel.Text &= "KeyCode: " & e.KeyCode.ToString() & _
37 "KeyValue: " & e.KeyValue.ToString()
43
*
*
*
Software Engineering Observation 14.3
*
*
14.13  Menus
*
*
Menu
*
14.13  Menus
To create a menu, drag a MenuStrip control onto the Form.
Click the Type Here TextBox (Fig. 14.43) and type the menu item’s name.
Fig. 14.43 | Editing menus in Visual Studio.
Type menu name
*
14.13  Menus (Cont.)
After you press the Enter key, the menu item name is added to the menu (Fig. 14.44).
Fig. 14.44 | Adding ToolStripMenuItems to a MenuStrip.
Place & character
TextBox for
adding another
top-level menu
*
*
14.13  Menus (Cont.)
To create an access shortcut (or keyboard shortcut), type an ampersand (&) before the character to be underlined.
To display an ampersand, type &&.
*
*
14.13  Menus (Cont.)
To add other shortcut keys, set the ShortcutKeys property of the appropriate ToolStripMenuItems.
In the window that appears (Fig. 14.45), use the CheckBoxes and drop-down list to select the shortcut keys.
Fig. 14.45 | Menu item options.
Setting modifier keys
shortcut key for the menu item)
*
*
14.13  Menus (Cont.)
Look-and-Feel Observation 14.8
*
*
Remove a menu item with the Delete key.
Separator bars are inserted by right clicking and selecting Insert > Separator or by typing “-” for the text of a menu item.
Clicking the down arrow on a new menu item (Fig. 14.46) allows you to select the type of item to add.
Fig. 14.46 | Menu item options.
Menu item options
*
14.13  Menus (Cont.)
*
Description
HasChildren
RightToLeft
ToolStripMenuItem Properties
CheckOnClick
Indicates that a menu item should appear checked or unchecked.
MenuItems
2009 Pearson Education, Inc. All rights reserved.
*
14.13  Menus (Cont.)
*
Description
ToolStripMenuItem Properties
ShortcutKey DisplayString
Specifies text that should appear beside a menu item for a shortcut key.
ShortcutKeys
ShowShortcutKeys
Indicates whether a shortcut key is shown beside the menu item text.
Text
Common ToolStripMenuItem Event
Click
Generated when an item is clicked or a shortcut key is used.
2009 Pearson Education, Inc. All rights reserved.
*
14.13  Menus (Cont.)
Look-and-Feel Observation 14.9
*
*
on a Form.
Handling a clicks on a MenuItem.
*
3 Public Class MenuTestForm
6 Private Sub aboutToolStripMenuItem_Click( _
8 Handles aboutToolStripMenuItem.Click
12 MessageBoxIcon.Information)
16 Private Sub exitToolStripMenuItem_Click( _
18 Handles exitToolStripMenuItem.Click
*
Changing font color when the Black MenuItem is checked.
*
24 Private Sub ClearColor()
25 ' clear all checkmarks
33 Private Sub blackToolStripMenuItem_Click( _
35 Handles blackToolStripMenuItem.Click
38 displayLabel.ForeColor = Color.Black ' set Color to Black
39 blackToolStripMenuItem.Checked = True
*
( 3 of 9 )
*
43 Private Sub blueToolStripMenuItem_Click( _
45 Handles blueToolStripMenuItem.Click
48 displayLabel.ForeColor = Color.Blue ' set Color to Blue
49 blueToolStripMenuItem.Checked = True
53 Private Sub redToolStripMenuItem_Click( _
55 Handles redToolStripMenuItem.Click
58 displayLabel.ForeColor = Color.Red ' set Color to Red
59 redToolStripMenuItem.Checked = True
*
Changing font family by changing the Font property.
*
63 Private Sub greenToolStripMenuItem_Click( _
65 Handles greenToolStripMenuItem.Click
68 displayLabel.ForeColor = Color.Green ' set Color to Green
69 greenToolStripMenuItem.Checked = True
73 Private Sub ClearFont()
78
79 ' update Menu state and set Font to Times New Roman
80 Private Sub timesToolStripMenuItem_Click( _
82 Handles timesToolStripMenuItem.Click
*
Changing font style by changing the Font property.
*
85 timesToolStripMenuItem.Checked = True
88 displayLabel.Font = _
90 End Sub ' timesToolStripMenuItem_Click
92 ' update Menu state and set Font to Courier New
93 Private Sub courierToolStripMenuItem_Click( _
95 Handles courierToolStripMenuItem.Click
98 courierToolStripMenuItem.Checked = True
*
( 6 of 9 )
*
103 End Sub ' courierToolStripMenuItem_Click
104
105 ' update Menu state and set Font to Comic Sans MS
106 Private Sub comicToolStripMenuItem_Click( _
108 Handles comicToolStripMenuItem.Click
111 comicToolStripMenuItem.Checked = True
114 displayLabel.Font = _
116 End Sub ' comicToolStripMenuItem_Click
*
Handling a clicks on a MenuItem.
*
119 Private Sub boldToolStripMenuItem_Click( _
121 Handles boldToolStripMenuItem.Click
123 boldToolStripMenuItem.Checked = Not boldToolStripMenuItem.Checked
125 ' use Xor to toggle bold, keep all other styles
126 displayLabel.Font = New Font(displayLabel.Font.FontFamily, 14, _
127 displayLabel.Font.Style Xor FontStyle.Bold)
128 End Sub ' boldToolStripMenuItem_Click
131 Private Sub italicToolStripMenuItem_Click( _
133 Handles italicToolStripMenuItem.Click
135 italicToolStripMenuItem.Checked = _
*
Outline
MenuTestForm.vb
( 8 of 9 )
*
138 ' use Xor to toggle italic, keep all other styles
139 displayLabel.Font = New Font(displayLabel.Font.FontFamily, 14, _
140 displayLabel.Font.Style Xor FontStyle.Italic)
141 End Sub ' italicToolStripMenuItem_Click
*
e) Program with bold red font
f) MessageBox displayed by File > About
Software Engineering Observation 14.4
by the MenuStrip. You must program this behavior.
Outline
MenuTestForm.vb
( 9 of 9 )
*
*
Fig. 14.49 | MonthCalendar control.
The MonthCalendar control (Fig. 14.49) displays a monthly calendar on the Form.
Current day is outlined
Selected day is highlighted
*
*
Description
FirstDayOfWeek
Sets which day of the week is the first for each week.
MaxDate
MaxSelectionCount
The maximum number of dates that can be selected at once.
MinDate
MonthlyBoldedDates
An array of dates that will displayed in bold in the calendar.
SelectionEnd
SelectionRange
SelectionStart
Common MonthCalendar Event
2009 Pearson Education, Inc. All rights reserved.
*
The DateTimePicker control is similar to the MonthCalendar control.
*
Description
CalendarMonth- Background
CustomFormat
Sets the custom format string for the user’s options.
Date
MaxDate
MinDate
2009 Pearson Education, Inc. All rights reserved.
*
14.15  DateTimePicker Control (Cont.)
*
Description
ShowUpDown
Used to indicate that the control should have up and down Buttons.
TimeOfDay
Common DateTimePicker Event
2009 Pearson Education, Inc. All rights reserved.
*
DateTimePicker control to select an item’s
drop-off date.
The date is always two days after drop off, or three
days if a Sunday is reached.
Accepting dates only after the present day.
Accepting dates only one year from the present day.
Outline
DateTimePicker
Test.vb
*
2 ' Using a DateTimePicker to select a drop off date.
3 Public Class DateTimePickerTest
8 dropOffDateTimePicker.MinDate = DateTime.Today
9
10 ' user can select days up to one year from now
11 dropOffDateTimePicker.MaxDate = DateTime.Today.AddYears(1)
*
Retrieving the selected date from the DateTimePicker’s Value property.
DateTime’s AddDays method increases the date by three days.
A String representing the delivery date is obtained by calling method ToLongDateString.
Outline
DateTimePicker
Test.vb
*
17 Handles dropOffDateTimePicker.ValueChanged
20
21 ' add an extra day when items are dropped off Friday-Sunday
22 If dropOffDate.DayOfWeek = DayOfWeek.Friday Or _
23 dropOffDate.DayOfWeek = DayOfWeek.Saturday Or _
24 dropOffDate.DayOfWeek = DayOfWeek.Sunday Then
26 outputLabel.Text = dropOffDate.AddDays(3).ToLongDateString()
28 outputLabel.Text = dropOffDate.AddDays(2).ToLongDateString()
29 End If
*
*
*
Fig. 14.53 | LinkLabel control in running program.
The LinkLabel control displays links to other resources, such as files or Web pages (Fig. 14.53).
When clicked, the LinkLabel generates a LinkClicked event.
Hand image displays when mouse moves over LinkLabel
LinkLabel on a Form
*
*
Description
LinkArea
Specifies which portion of the text is part of the link.
LinkBehavior
LinkColor
Specifies the original color of all links before they have been visited. The default color is set by the system, but is usually blue.
LinkVisited
If True, the link appears as though it has been visited.
Text
UseMnemonic
If True, the & character can be used to create a shortcut.
VisitedLinkColor
Common Event (event argument type is LinkLabelLinkClickedEventArgs)
LinkClicked
2009 Pearson Education, Inc. All rights reserved.
*
Look-and-Feel Observation 14.10
*
*
Opening a drive with a LinkLabel.
Outline
LinkLabelTest
Form.vb
( 1 of 5 )
*
3
8 Handles cDriveLinkLabel.LinkClicked
11 Process.Start("C:\")
17 Handles deitelLinkLabel.LinkClicked
*
Opening an application with a LinkLabel.
Outline
LinkLabelTest
Form.vb
( 2 of 5 )
*
20 Process.Start("IExplore", "http://www.deitel.com")
24 Private Sub notepadLinkLabel_LinkClicked(ByVal sender As _
25 System.Object, ByVal e As LinkLabelLinkClickedEventArgs) _
26 Handles notepadLinkLabel.LinkClicked
29 Process.Start("notepad")
*
Click first LinkLabel to look at contents of C: drive
Outline
LinkLabelTest
Form.vb
( 3 of 5 )
*
*
Outline
LinkLabelTest
Form.vb
( 4 of 5 )
*
*
Outline
LinkLabelTest
Form.vb
( 5 of 5 )
*
*
Fig. 14.56 | ListBox and CheckedListBox on a Form.
A ListBox allows the user to view and select multiple items in a list.
A CheckedListBox has CheckBoxes next to each item in the list.
Selected items
Scrollbars appear
if necessary
*
14.17  ListBox Control (Cont.)
*
Description
MultiColumn
Indicates whether the ListBox can break a list into multiple columns.
SelectedIndex
Returns the index of the selected item, or -1 if no items have been selected.
SelectedIndices
Returns a collection containing the indices of all selected items.
SelectedItem
*
14.17  ListBox Control (Cont.)
*
Description
SelectionMode
Determines the number of items that can be selected and the means through which multiple items can be selected.
Sorted
Common Methods
GetSelected
Returns True if the item at the argument’s index is selected.
Common Event
2009 Pearson Education, Inc. All rights reserved.
*
14.17  ListBox Control (Cont.)
To add items to a ListBox or to a CheckedListBox, call method Add:
myListBox.Items.Add( myListItem )
Add items to ListBoxes and CheckedListBoxes by examining the Items property in the Properties window (Fig. 14.58).
Fig. 14.58 | String Collection Editor.
*
*
Adding the text input as a ListBox item.
Removing the selected item from a ListBox if any item is selected.
Outline
ListBoxTestForm.vb
ListBox items. (Part 1 of 3.)
*
3 Public Class ListBoxTestForm
4 ' add to displayListBox the item the user enters in inputTextBox,
5 ' then clear inputTextBox
8
13 ' remove an item from displayListBox if one is selected
14 Private Sub removeButton_Click(ByVal sender As System.Object, _
15 ByVal e As System.EventArgs) Handles removeButton.Click
16
18 If displayListBox.SelectedIndex <> -1 Then
19 displayListBox.Items.RemoveAt(displayListBox.SelectedIndex)
*
ListBox items. (Part 2 of 3.)
*
26
33
*
b) Adding values to the list
d) Empty list
ListBox items. (Part 3 of 3.)
*
*
14.18  CheckedListBox Control
The CheckedListBox control derives from class ListBox and includes a CheckBox next to each item.
*
Description
(All the ListBox properties, methods and events are inherited by CheckedListBox.)
CheckedItems
CheckedIndices
CheckOnClick
SelectionMode
Common Method
2009 Pearson Education, Inc. All rights reserved.
*
14.18  CheckedListBox Control (Cont.)
*
Description
ItemCheck
ItemCheckEventArgs Properties
Index
NewValue
*
14.18  CheckedListBox Control (Cont.)
Common Programming Error 14.1
The IDE displays an error message if you attempt to set
the SelectionMode property to MultiSimple or MultiExtended in the Properties window of a CheckedListBox. If this value is set programmatically,
a runtime error occurs.
*
unchecks a CheckedListBox item.
Putting the item in the ListBox if the item is checked, and removing the item if it is unchecked.
Retrieving the text of a selected CheckedListBox item.
Outline
CheckedListBoxTestForm.vb
( 1 of 2 )
*
1 ' Fig. 14.61: CheckedListBoxTestForm.vb
2 ' Using the checked ListBox to add items to a display ListBox
3 Public Class CheckedListBoxTestForm
4 ' add an item to or remove an item from lstDisplay
5 Private Sub itemCheckedListBox_ItemCheck( _
7 Handles itemCheckedListBox.ItemCheck
11
12 ' if the selected item is checked add it to displayListBox;
13 ' otherwise, remove it from displayListBox
14 If e.NewValue = CheckState.Checked Then
15 displayListBox.Items.Add(item)
16 Else
17 displayListBox.Items.Remove(item)
*
d) Checking an item
Outline
CheckedListBoxTestForm.vb
( 2 of 2 )
*
*
The ComboBox control combines TextBox features with a drop-down list.
By default, the user can enter text into the TextBox or click the down arrow to display a list of predefined items.
Figure 14.62 shows a sample ComboBox in three different states.
Fig. 14.62 | ComboBox demonstration.
list changes text in TextBox portion
Click the down arrow to
display items in drop-down list
*
*
*
Description
Items
MaxDropDownItems
Specifies the maximum number of items that the drop-down list can display.
SelectedIndex
SelectedItem
Sorted
Common Event
2009 Pearson Education, Inc. All rights reserved.
*
Option Simple displays a scrollbar next to the control.
Style DropDown (default) displays a drop-down list. The user can type a new item in the ComboBox.
*
*
( 1 of 3 )
*
3 Public Class ComboBoxTest
4 ' get index of selected shape, then draw the shape
5 Private Sub imageComboBox_SelectedIndexChanged( _
7 Handles imageComboBox.SelectedIndexChanged
9 Dim myGraphics As Graphics = MyBase.CreateGraphics()
10
12 Dim myPen As Pen = New Pen(Color.DarkRed)
13
15 Dim mySolidBrush As SolidBrush = New SolidBrush(Color.DarkRed)
16
18 myGraphics.Clear(Color.White)
*
Retrieving the index of an item selected from the ComboBox.
Drawing a shape at specific coordinates.
Outline
ComboBoxTest.vb
( 2 of 3 )
*
21 Select Case imageComboBox.SelectedIndex
23 myGraphics.DrawEllipse(myPen, 50, 50, 150, 150)
24 Case 1 ' case Rectangle is selected
25 myGraphics.DrawRectangle(myPen, 50, 50, 150, 150)
26 Case 2 ' case Ellipse is selected
27 myGraphics.DrawEllipse(myPen, 50, 85, 150, 115)
28 Case 3 ' case Pie is selected
29 myGraphics.DrawPie(myPen, 50, 50, 150, 150, 0, 45)
30 Case 4 ' case Filled Circle is selected
31 myGraphics.FillEllipse(mySolidBrush, 50, 50, 150, 150)
32 Case 5 ' case Filled Rectangle is selected
33 myGraphics.FillRectangle(mySolidBrush, 50, 50, 150, 150)
34 Case 6 ' case Filled Ellipse is selected
35 myGraphics.FillEllipse(mySolidBrush, 50, 85, 150, 115)
36 Case 7 ' case Filled Pie is selected
37 myGraphics.FillPie(mySolidBrush, 50, 50, 150, 150, 0, 45)
38 End Select
41 End Sub ' imageComboBox_SelectedIndexChanged
42 End Class ' ComboBoxTest
*
c) Selecting a filled square
Outline
ComboBoxTest.vb
( 3 of 3 )
*
*
program is designed to accept user-submitted elements.
*
*
The TreeView control displays nodes hierarchically in a tree.
A parent node can be expanded or collapsed by clicking the plus box or minus box to its left.
Fig. 14.65 | TreeView displaying a sample tree.
Root node
Child nodes (of Manager1)
*
*
Description
ImageList
Nodes
SelectedNode
AfterSelect
2009 Pearson Education, Inc. All rights reserved.
*
*
FirstNode
FullPath
Indicates the path of the node, starting at the root.
ImageIndex
Specifies the index of the image shown when the node is deselected.
LastNode
NextNode
Nodes
Collection of the current node’s child TreeNodes with methods Add, Clear and Remove.
2009 Pearson Education, Inc. All rights reserved.
*
Fig. 14.67 | TreeNode properties and methods. (Part 2 of 2.)
14.20   TreeView Control (Cont.)
PrevNode
SelectedImageIndex
Specifies the index of the image to use when the node is selected.
Text
Common Methods
GetNodeCount
2009 Pearson Education, Inc. All rights reserved.
*
14.20  TreeView Control (Cont.)
To use the TreeNode Editor (Fig. 14.68), click the ellipsis next to the Nodes property in the Properties window.
Fig. 14.68 | TreeNode Editor.
*
TreeNode object and pass it a String to display.
Call Add to add a new TreeNode to the TreeView’s Nodes collection:
myTreeView.Nodes.Add(rootLabel)
by writing
myTreeView.Nodes(myIndex)
To add a child to the root node at index myIndex, write myTreeView.Nodes(myIndex). Nodes.Add(childNodeText)
14.20  TreeView Control (Cont.)
*
Removing all items from the TreeView.
Outline
TreeViewDirectory
Structure.vb
( 1 of 4 )
*
3 Imports System.IO
7 Private Sub enterButton_Click(ByVal sender As System.Object, _
8 ByVal e As System.EventArgs) Handles enterButton.Click
9
11
12 ' if the directory specified by the user exists, fill in the
13 ' TreeView; otherwise, display an error message
14 If (Directory.Exists(inputTextBox.Text)) Then
16 directoryTreeView.Nodes.Add(inputTextBox.Text)
21 MessageBox.Show(inputTextBox.Text & " could not be found.", _
22 "Directory Not Found", MessageBoxButtons.OK, _
23 MessageBoxIcon.Error)
*
Outline
TreeViewDirectory
Structure.vb
( 2 of 4 )
*
28 Private Sub PopulateTreeView( _
30 ' array stores all subdirectories in the directory
31 Dim directoryArray As String() = _
32 Directory.GetDirectories(directoryValue)
35 Try
37 If directoryArray.Length <> 0 Then
38 ' for every subdirectory, create new TreeNode,
39 ' add as a child of current node and recursively
40 ' populate child nodes with subdirectories
41 For Each directory In directoryArray
42 ' obtain last part of path name from the full path name
43 ' by calling the GetFileNameWithoutExtension method of the
44 ' Path class
46 Path.GetFileNameWithoutExtension(directory)
*
Adding the processed TreeNode.
Outline
TreeViewDirectory
Structure.vb
( 3 of 4 )
*
49 Dim myNode As TreeNode = New TreeNode(directoryName)
50
52 parentNode.Nodes.Add(myNode)
55 PopulateTreeView(directory, myNode)
59 parentNode.Nodes.Add("Access denied")
60 End Try
*
( 4 of 4 )
*
*
14.21  ListView Control
Fig. 14.70 | ListView properties and an event. (Part 1 of 2)
*
Description
CheckBoxes
LargeImageList
Items
MultiSelect
2009 Pearson Education, Inc. All rights reserved.
*
14.21  ListView Control (Cont.)
*
Description
SmallImageList
View
2009 Pearson Education, Inc. All rights reserved.
*
14.21  ListView Control (Cont.)
Create an ImageList by dragging it to a Form from the ToolBox.
Select the Images property to display the Image Collection Editor (Fig. 14.71).
*
*
Adding Images to the ListView to represent directories and files.
Outline
ListViewTest
Form.vb
( 1 of 6 )
*
3 Imports System.IO
8
10 ' (i.e., the one from which the application is executed)
11 Private Sub ListViewTest_Load(ByVal sender As Object, _
12 ByVal e As System.EventArgs) Handles Me.Load
13
16 Dim folderImageResource = My.Resources.ResourceManager.GetObject( _
21 ' convert picture resources to Images and load into PictureBoxes
22 fileFolderImageList.Images.Add(CType(folderImageResource, Image))
23 fileFolderImageList.Images.Add(CType(fileImageResource, Image))
*
Determining if any items are selected.
String chosen is assigned the text of the first selected item
Determining whether the user chose the first item.
Outline
ListViewTest
Form.vb
( 2 of 6 )
*
26 LoadFilesInDirectory(currentDirectory)
30 ' browse directory user clicked or go up one level
31 Private Sub browserListView_Click(ByVal sender As System.Object, _
32 ByVal e As System.EventArgs) Handles browserListView.Click
33 ' ensure an item is selected
34 If browserListView.SelectedItems.Count <> 0 Then
35 ' if first item selected, go up one level
36 If browserListView.Items(0).Selected Then
38 Dim directoryObject As DirectoryInfo = _
39 New DirectoryInfo(currentDirectory)
42 If directoryObject.Parent IsNot Nothing Then
43 LoadFilesInDirectory(directoryObject.Parent.FullName)
47 ' directory or file chosen
48 Dim chosen As String = browserListView.SelectedItems(0).Text
2009 Pearson Education, Inc. All rights reserved.
*
Outline
ListViewTest
Form.vb
( 3 of 6 )
*
51 If Directory.Exists( _
65 Private Sub LoadFilesInDirectory( _
67 ' load directory information and display
68 Try
70 browserListView.Items.Clear()
2009 Pearson Education, Inc. All rights reserved.
*
Adding a folder icon to any subdirectories.
Adding any files in the directory to the ListView.
Outline
ListViewTest
Form.vb
( 4 of 6 )
*
76 New DirectoryInfo(currentDirectory)
79 Dim directoryArray As DirectoryInfo() = _
80 newCurrentDirectory.GetDirectories()
82
85 ' add directory to ListView
86 Dim newDirectoryItem As ListViewItem = _
87 browserListView.Items.Add(dir.Name)
90 Next
94 ' add file to ListView
95 Dim newFileItem As ListViewItem = _
96 browserListView.Items.Add(file.Name)
*
( 5 of 6 )
*
99 Next
101 MessageBox.Show("Warning: Some files may not be " & _
102 "visible due to permission settings", _
103 "Attention", 0, MessageBoxIcon.Warning)
*
b) Navigating the file
Outline
ListViewTest
Form.vb
( 6 of 6 )
*
*
14.21  ListView Control (Cont.)
To add the icons for folders and files, add images from the bin\Debug folder of this example to the project’s Resources.
Set the object browserListView property SmallImageList to an ImageList by using the Properties window.
Software Engineering Observation 14.5
*
*
14.22  TabControl Control
Tabbed windows are used in several applications, including Visual Studio (Fig. 14.73).
Fig. 14.73 | Tabbed windows in Visual Studio.
Tabs
*
Fig. 14.74 | TabControl with TabPages example.
TabPage
*
14.22  TabControl Control (Cont.)
Add TabControls by dragging and dropping them onto a Form in Design mode.
To add TabPages in Design mode, right click the TabControl and select Add Tab (Fig. 14.75).
Fig. 14.75 | TabPages added to a TabControl.
*
*
*
ItemSize
SelectedIndex
SelectedTab
TabPages
Common Event
2009 Pearson Education, Inc. All rights reserved.
*
myTabPage.Controls.Add(myControl)
myTabControl.TabPages.Add(myTabPage)
Outline
UsingTabsForm.vb
( 1 of 7 )
*
3 Public Class UsingTabsForm
5 Private Sub blackRadioButton_CheckedChanged( _
7 Handles blackRadioButton.CheckedChanged
10 End Sub ' blackRadioButton_CheckedChanged
13 Private Sub redRadioButton_CheckedChanged( _
15 Handles redRadioButton.CheckedChanged
18 End Sub ' redRadioButton_CheckedChanged
*
( 2 of 7 )
*
21 Private Sub greenRadioButton_CheckedChanged( _
23 Handles greenRadioButton.CheckedChanged
26 End Sub ' greenRadioButton_CheckedChanged
29 Private Sub size12RadioButton_CheckedChanged( _
31 Handles size12RadioButton.CheckedChanged
33 displayLabel.Font = New Font(displayLabel.Font.Name, 12)
34 End Sub ' size12RadioButton_CheckedChanged
37 Private Sub size16RadioButton_CheckedChanged( _
39 Handles size16RadioButton.CheckedChanged
2009 Pearson Education, Inc. All rights reserved.
*
( 3 of 7 )
*
42 End Sub ' size16RadioButton_CheckedChanged
45 Private Sub size20RadioButton_CheckedChanged( _
47 Handles size20RadioButton.CheckedChanged
49 displayLabel.Font = New Font(displayLabel.Font.Name, 20)
50 End Sub ' size20RadioButton_CheckedChanged
53 Private Sub helloRadioButton_CheckedChanged( _
55 Handles helloRadioButton.CheckedChanged
58 End Sub ' helloRadioButton_CheckedChanged
2009 Pearson Education, Inc. All rights reserved.
*
( 4 of 7 )
*
63 Handles goodbyeRadioButton.CheckedChanged
66 End Sub ' goodbyeRadioButton_CheckedChanged
67 End Class ' UsingTabsForm
*
( 5 of 7 )
*
*
( 6 of 7 )
*
*
Software Engineering Observation 14.6
*
*
14.23  Multiple Document Interface (MDI) Windows
Multiple document interfaces (MDIs) allow users to edit multiple documents at once.
*
*
Fig. 14.78 | MDI parent window and MDI child windows.
MDI parent
MDI child
MDI child
*
Fig. 14.79 | SDI and MDI forms.
Single Document Interface (SDI)
To create an MDI Form, create a new Form and set its IsMdiContainer property to True (Fig. 14.79).
Multiple Document Interface (MDI)
*
14.23  Multiple Document Interface (MDI) Windows (Cont.)
To make a Form into a child, set its MdiParent property to the parent Form:
Dim childForm As New ChildFormClass()
childForm.MdiParent = parentForm
childForm.Show()
*
*
14.23  Multiple Document Interface (MDI) Windows
*
Description
MdiParent
Common MDI Parent Properties
Returns the Form that is the currently active MDI child.
IsMdiContainer
MdiChildren
Common Method
Common Event
2009 Pearson Education, Inc. All rights reserved.
*
Parent title bar indicates
Maximized child window icons:
minimize, restore and close
*
Fig. 14.82 | MenuStrip property MdiWindowListItem example. (Part 1 of 2.)
Property MdiWindowListItem specifies a menu for displaying a list of open child windows (Fig. 14.82).
child windows list
*
Nine or more child
*
*
Good Programming Practice 14.2
*
*
14.23  Multiple Document Interface (MDI) Windows (Cont.)
MDI containers allow you to organize child windows by calling method LayoutMdi with one of the MdiLayout constants.
Figure 14.83 illustrates the values of the MdiLayout enumeration.
*
*
a) Arrange Icons
*
*
c) TileHorizontal
d) TileVertical
*
*
MDI parent Form.
*
3 Public Class UsingMDIForm
5 Private Sub csToolStripMenuItem_Click(ByVal sender As System.Object, _
6 ByVal e As System.EventArgs) Handles csToolStripMenuItem.Click
7 ' create new child
8 Dim child As New ChildForm("Visual C# 2008 How to Program", _
9 "vcs2008htp")
11 child.Show() ' display child
12 End Sub ' csToolStripMenuItem_Click
15 Private Sub cppToolStripMenuItem_Click( _
17 Handles cppToolStripMenuItem.Click
*
*
18 ' create new child
19 Dim child As New ChildForm("Visual C++ 2008 How to Program", _
20 "vcpp2008htp")
22 child.Show() ' display child
23 End Sub ' cppToolStripMenuItem_Click
26 Private Sub vbToolStripMenuItem_Click(ByVal sender As System.Object, _
27 ByVal e As System.EventArgs) Handles vbToolStripMenuItem.Click
28 ' create new child
29 Dim child As New ChildForm("Visual Basic 2008 How to Program", _
30 "vb2008htp")
32 child.Show() ' display child
33 End Sub ' vbToolStripMenuItem_Click
38 Handles exitToolStripMenuItem.Click
*
*
46 Handles cascadeToolStripMenuItem.Click
54 Handles tileHorizontalToolStripMenuItem.Click
*
*
62 Handles tileVerticalToolStripMenuItem.Click
*
*
*
c)
d)
*
ChildForm.vb
Outline
*
3 Imports System.IO
5 Public Class ChildForm
6 Public Sub New(ByVal title As String, ByVal fileName As String)
7 ' ensure that Designer generated code executes
8 InitializeComponent()
10
12 Dim pictureResource = My.Resources.ResourceManager.GetObject( _
15 ' convert pictureResource to image type and load into PictureBox
16 displayPictureBox.Image = CType(pictureResource, Image)
17 End Sub ' New
18 End Class ' ChildForm
*
a common look-and-feel. .
*
3 Public Class VisualInheritanceForm
7
8 MessageBox.Show( _
9 "Bugs, Bugs, Bugs is a product of Deitel & Associates, Inc.", _
10 "Learn More", MessageBoxButtons.OK, _
*
*
*
14.24  Visual Inheritance (Cont.)
Right click the project name in the Solution Explorer and select Properties, then choose the Application tab.
In the Application type drop-down list, change Windows Application to Class Library.
Building the project produces a .dll.
*
*
14.24  Visual Inheritance (Cont.)
To visually inherit from VisualInheritanceForm, add a reference to the .dll you just created, and add the line:
Inherits VisualInheritance.VisualInheritanceForm.
*
Fig. 14.87 | Form demonstrating visual inheritance.
*
*
*
3 Public Class VisualInheritanceTestForm
7
10 "About this Program", MessageBoxButtons.OK, _
11 MessageBoxIcon.Information)
*
*
*
14.25  User-Defined Controls
The simplest way to create a custom control is to derive a class from an existing control, such as a Label.
All controls contain method OnPaint, which the system calls when a component must be redrawn.
Method OnPaint is passed a PaintEventArgs object, which contains graphics information.
*
*
*
Description
Inherit from Windows Forms control
Adds functionality to a pre-existing control. Override OnPaint, and call the base class’s OnPaint method. Note that you only can add to the original control’s appearance.
Create a UserControl
Create a UserControl composed of multiple pre-existing controls. You must place drawing code in a Paint event handler. Again, note that you only can add to the original control’s appearance.
Inherit from class Control
Define a brand-new control. Override method OnPaint, then call base class method OnPaint and include methods to draw the control.
PaintEventArgs Properties
ClipRectangle
2009 Pearson Education, Inc. All rights reserved.
*
Label and a Timer.
*
3 Public Class ClockUserControl
7 ' get current time (Now), convert to String
8 displayLabel.Text = DateTime.Now.ToLongTimeString()
*
*
*
Create the ClockUserControl class by selecting Project > Add User Control ….
*
*
14.25  User-Defined Controls (Cont.)
Visual Studio allows you to share custom controls with other developers:
Create a new Class Library project and delete Class1.vb.
Add a user control file and create your custom control (Fig. 14.91).
Fig. 14.91 | Custom-control creation.
*
Build the project and create a new Windows Forms application.
Right click the Toolbox and select Choose Items….
Click Browse... and select the .dll file for the class library (Fig. 14.92).
Fig. 14.92 | Custom control added to the ToolBox.
*
*
New ToolBox icon
Custom control dragged onto a Form
*
TextBox
Button
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 i tem in the list.
Panel
A container in which controls can be placed and organized.
NumericUpDown
Enables the user to select from a range of numeric input values.
Form properties,
AutoScroll
when needed.
pressed.
FormBorderStyle
Font
Text
Form properties,
Hide
Hides a Form, but does not destroy the Form or
release its resources.
1 ' Fig. 14.5: SimpleEventExampleForm.vb
3 Public Class SimpleEventExampleForm
5 Private Sub clickMeButton_Click( ByVal sender As System.Object, _
6 ByVal e As System.EventArgs) Handles clickMeButton.Click
7
BackgroundImage
Enabled
Focused
Font
ForeColor
determines text color.
TabStop
If True, then a user can give focus to this control
via the Tab key.
Visible
Common Methods
False).
Show
True).
properties
Description
Anchor
Causes a control to remain at a fixed distance from the side(s).
Dock
Allows a control to span one side or fill its container.
Padding
Sets the space between a container’s edges and docked controls.
Location
Specifies the location (as a set of coordinates) of the control.
Size
Specifies the size of the control in pixels as a Size object.
MinimumSize,
MaximumSize
Common Label
Text
TextAlign
The alignment of the Label’s text on the control—
horizontally (left, center or right) and vertically (top, middle
or bottom).
TextBox properties
AcceptsReturn
If True in a multiline TextBox, pressing Enter creates a new line.
Multiline
UseSystem-
PasswordChar
ReadOnly
ScrollBars
appear.
Text
Common Event
Event generated when the text ch anges in a TextBox.
Button properties
FlatStyle
Common Event
1 ' Fig. 14.21: LabelTextBoxButtonTestForm.vb
3 ' the hidden text in a password TextBox.
4 Public Class LabelTextBoxButtonTestForm
6 Private Sub displayPasswordButton_Click( _
8 Handles displayPasswordButton.Click
10 displayPasswordLabel.Text = inputPasswordTextBox.Text
Text
Panel properties Description
Indicates whether scrollbars appear when the Panel is too small
to display all of its controls.
BorderStyle
Controls
1 ' Fig. 14.25: GroupboxPanelExampleForm.vb
3 Public Class GroupBoxPanelExampleForm
7 messageLabel.Text = "Hi pressed" ' change text in Label
8 End Sub ' hiButton_Click
13 messageLabel.Text = "Bye pressed" ' change text in Label
14 End Sub ' byeButton_Click
19 messageLabel.Text = "Far left pressed" ' change text in Label
20 End Sub ' leftButton_Click
25 messageLabel.Text = "Far right pressed" ' change text in Label
26 End Sub ' rightButton_Click
27 End Class ' GroupBoxPanelExampleForm
CheckState
Indeterminate.
Text
Specifies the text displayed to the right of the CheckBox.
Common Events
CheckBox’s default event.
1 ' Fig. 14.27: CheckBoxTestForm.vb
3 Public Class CheckBoxTestForm
6 Private Sub boldCheckBox_CheckedChanged( _
8 Handles boldCheckBox.CheckedChanged
16 Private Sub italicCheckBox_CheckedChanged( _
18 Handles italicCheckBox.CheckedChanged
Text
Common Event
1 ' Fig. 14.29: RadioButtonsTestForm.vb
3 Public Class RadioButtonsTestForm
4 ' create variables that store the user's choice of options
5 Private iconType As MessageBoxIcon
6 Private buttonType As MessageBoxButtons
7
9 Private Sub okRadioButton_CheckedChanged( _
11 Handles okRadioButton.CheckedChanged
12 buttonType = MessageBoxButtons.OK
16 Private Sub okCancelRadioButton_CheckedChanged( _
18 Handles okCancelRadioButton.CheckedChanged
19 buttonType = MessageBoxButtons.OKCancel
23 Private Sub abortRetryIgnoreRadioButton_CheckedChanged( _
25 Handles abortRetryIgnoreRadioButton.CheckedChanged
26 buttonType = MessageBoxButtons.AbortRetryIgnore
30 Private Sub yesNoCancelRadioButton_CheckedChanged( _
32 Handles yesNoCancelRadioButton.CheckedChanged
33 buttonType = MessageBoxButtons.YesNoCancel
37 Private Sub yesNoRadioButton_CheckedChanged( _
39 Handles yesNoRadioButton.CheckedChanged
40 buttonType = MessageBoxButtons.YesNo
44 Private Sub retryCancelRadioButton_CheckedChanged( _
46 Handles retryCancelRadioButton.CheckedChanged
47 buttonType = MessageBoxButtons.RetryCancel
51 Private Sub asteriskRadioButton_CheckedChanged( _
53 Handles asteriskRadioButton.CheckedChanged
54 iconType = MessageBoxIcon.Asterisk
58 Private Sub errorRadioButton_CheckedChanged( _
60 Handles errorRadioButton.CheckedChanged
61 iconType = MessageBoxIcon.Error
65 Private Sub exclamationRadioButton_CheckedChanged( _
67 Handles exclamationRadioButton.CheckedChanged
68 iconType = MessageBoxIcon.Exclamation
72 Private Sub handRadioButton_CheckedChanged( _
74 Handles handRadioButton.CheckedChanged
75 iconType = MessageBoxIcon.Hand
79 Private Sub informationRadioButton_CheckedChanged( _
81 Handles informationRadioButton.CheckedChanged
82 iconType = MessageBoxIcon.Information
86 Private Sub questionRadioButton_CheckedChanged( _
88 Handles questionRadioButton.CheckedChanged
89 iconType = MessageBoxIcon.Question
93 Private Sub stopRadioButton_CheckedChanged( _
95 Handles stopRadioButton.CheckedChanged
96 iconType = MessageBoxIcon.Stop
100 Private Sub warningRadioButton_CheckedChanged( _
102 Handles warningRadioButton.CheckedChanged
103 iconType = MessageBoxIcon.Warning
109 ' display MessageBox and store
110 ' the value of the Button that was pressed
111 Dim result As DialogResult = MessageBox.Show( _
112 "This is your custom MessageBox.", _
113 "Custom MessageBox", buttonType, iconType, 0, 0)
114
115 ' check to see which Button was pressed in the MessageBox
116 ' change text displayed accordingly
117 Select Case result
120 Case DialogResult.Cancel
122 Case DialogResult.Abort
124 Case DialogResult.Retry
126 Case DialogResult.Ignore
128 Case DialogResult.Yes
130 Case DialogResult.No
132 End Select
SizeMode
Common Event
1 ' Fig. 14.31: PictureBoxTestForm.vb
3 Imports System.IO
8
10 Private Sub nextButton_Click(ByVal sender As System.Object, _
11 ByVal e As System.EventArgs) Handles nextButton.Click
12
13 imageNum = (imageNum + 1) Mod 3 ' imageNum cycles from 0 to 2
14
16 Dim pictureResource = My.Resources.ResourceManager.GetObject( _
17 String.Format("image{0}", imageNum))
19 ' convert pictureResource to image type and load into PictureBox
20 imagePictureBox.Image = CType(pictureResource, Image)
21 End Sub ' nextButton_Click
22 End Class ' PictureBoxTestForm
AutoPopDelay
The amount of time (in milliseconds) that the tool tip appears.
InitialDelay
The amount of time that a mouse must hover over a control
before a tool tip appears.
ReshowDelay
The amount of time between two different tool tips appearing.
Common Event
1 ' Fig. 14.33: ToolTipDemonstrationForm.vb
3 Public Class ToolTipDemonstrationForm
5 End Class ' ToolTipDemonstrationForm
Increment
when the user clicks the up and down arrows.
Maximum
Minimum
UpDownAlign
Value
Common Event
ValueChanged
This event is raised when the value in the control is
changed.
3 Public Class NumericUpDownTestForm
6 ByVal e As System.EventArgs) Handles calculateButton.Click
7 ' declare variables to store user input
8 Dim principal As Decimal ' store principal
9 Dim rate As Double ' store interest rate
10 Dim year As Integer ' store number of years
11 Dim amount As Decimal ' store amount
12
20 vbNewLine
22 ' calculate amount after each year and append to output
23 For yearCounter As Integer = 1 To year
24 amount = principal * Convert.ToDecimal( _
26 displayTextBox.Text &= (yearCounter & vbTab & _
28 Next
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 TypeMouseEventArgs
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 within the
control’s boundaries.
Class MouseEventArgs Properties
Specifies which mouse button was pressed ( Left, Right, Middle or
none).
Clicks
X
Y
1 ' Fig. 14.39: PaintForm.vb
3 Public Class PaintForm
4 Private shouldPaint As Boolean = False ' determines whether to paint
5
7 Private Sub PaintForm_MouseDown(ByVal sender As System.Object, _
8 ByVal e As MouseEventArgs) Handles MyBase.MouseDown
9 shouldPaint = True
14 ByVal e As MouseEventArgs) Handles MyBase.MouseUp
15 shouldPaint = False
17
18 ' draw circle whenever mouse moves with its button held down
19 Private Sub Paint_MouseMove(ByVal sender As System.Object, _
20 ByVal e As MouseEventArgs) Handles MyBase.MouseMove
21 ' check if mouse button is being presse d
22 If (shouldPaint) Then
23 ' draw a circle where the mouse pointer is present
24 Dim g As Graphics = CreateGraphics()
25 g.FillEllipse( _
27 g.Dispose()
Key Events with Event Arguments of Type KeyEventArgs
KeyDown
KeyUp
Key Event with Event Argument of Type KeyPressEventArg s
KeyPress
Class KeyPressEventArgs Properties
Handled
Keyboard events and event arguments
Class KeyEventArgs Properties
Control
Shift
Handled
KeyCode
Returns the key code for the key as a value from the Keys enumeration.
KeyData
Returns the key code for a key combined with modifier information as a Keys
value.
KeyValue
Returns the key code as an int, rather than as a value from the Keys
enumeration.
Modifiers
Returns a Keys value indicating any pressed modifier keys ( Alt, Ctrl and Shift).
1 ' Fig. 14.41: KeyDemoForm.vb
3 Public Class KeyDemoForm
6 Private Sub KeyDemoForm_KeyPress( ByVal sender As System.Object, _
7 ByVal e As KeyPressEventArgs) Handles MyBase.KeyPress
8
10 End Sub ' KeyDemoForm_KeyPress
11
12 ' display modifier keys, key code, key data and key value
13 Private Sub KeyDemoForm_KeyDown(ByVal sender As System.Object, _
14 ByVal e As KeyEventArgs) Handles MyBase.KeyDown
15
17 keyInfoLabel.Text = "Alt: Yes" & vbNewLine
18 Else ' key is not Alt
19 keyInfoLabel.Text = "Alt: No" & vbNewLine
20 End If
23 keyInfoLabel.Text &= "Shift: Yes" & vbNewLine
24 Else ' key is not Shift
25 keyInfoLabel.Text &= "Shift: No" & vbNewLine
26 End If
29 keyInfoLabel.Text &= "Control: Yes" & vbNewLine
30 Else ' key is not Control
31 keyInfoLabel.Text &= "Control: No" & vbNewLine
32 End If
35 keyInfoLabel.Text &= "KeyCode: " & e.KeyCode.ToString() & _
37 "KeyValue: " & e.KeyValue.ToString()
43
MenuStrip Properties
HasChildren
RightToLeft
ToolStripMenuItem Properties
CheckOnClick
Indicates that a menu item should appear checked or unchecked.
MenuItems
MenuStrip and
ToolStripMenuItem Properties
ShortcutKey
DisplayString
Specifies text that should appear beside a menu item for a
shortcut key.
ShowShortcutKeys
Indicates whether a shortcut key is shown beside the menu item
text.
Text
Common ToolStripMenuItem Event
Click
Generated when an item is clicked or a shortcut key is used.
1 ' Fig. 14.48: MenuTestForm.vb
3 Public Class MenuTestForm
6 Private Sub aboutToolStripMenuItem_Click( _
8 Handles aboutToolStripMenuItem.Click
11 "of using menus.", "About", MessageBoxButtons.OK , _
12 MessageBoxIcon.Information)
16 Private Sub exitToolStripMenuItem_Click( _
18 Handles exitToolStripMenuItem.Click
24 Private Sub ClearColor()
25 ' clear all checkmarks
33 Private Sub blackToolStripMenuItem_Click( _
35 Handles blackToolStripMenuItem.Click
38 displayLabel.ForeColor = Color.Black ' set Color to Black
39 blackToolStripMenuItem.Checked = True
43 Private Sub blueToolStripMenuItem_Click( _
45 Handles blueToolStripMenuItem.Click
48 displayLabel.ForeColor = Color.Blue ' set Color to Blue
49 blueToolStripMenuItem.Checked = True
53 Private Sub redToolStripMenuItem_Click( _
55 Handles redToolStripMenuItem.Click
58 displayLabel.ForeColor = Color.Red ' set Color to Red
59 redToolStripMenuItem.Checked = True
63 Private Sub greenToolStripMenuItem_Click( _
65 Handles greenToolStripMenuItem.Click
68 displayLabel.ForeColor = Color.Green ' set Color to Green
69 greenToolStripMenuItem.Checked = True
73 Private Sub ClearFont()
78
79 ' update Menu state and set Font to Times New Roman
80 Private Sub timesToolStripMenuItem_Click( _
82 Handles timesToolStripMenuItem.Click
85 timesToolStripMenuItem.Checked = True
88 displayLabel.Font = _
90 End Sub ' timesToolStripMenuItem_Click
92 ' update Menu state and set Font to Courier New
93 Private Sub courierToolStripMenuItem_Click( _
95 Handles courierToolStripMenuItem.Click
98 courierToolStripMenuItem.Checked = True
103 End Sub ' courierToolStripMenuItem_Click
104
105 ' update Menu state and set Font to Comic Sans MS
106 Private Sub comicToolStripMenuItem_Click( _
108 Handles comicToolStripMenuItem.Click
111 comicToolStripMenuItem.Checked = True
114 displayLabel.Font = _
116 End Sub ' comicToolStripMenuItem_Click
119 Private Sub boldToolStripMenuItem_Click( _
121 Handles boldToolStripMenuItem.Click
123 boldToolStripMenuItem.Checked = Not boldToolStripMenuItem.Checked
125 ' use Xor to toggle bold, keep all other styles
126 displayLabel.Font = New Font(displayLabel.Font.FontFamily, 14, _
127 displayLabel.Font.Style Xor FontStyle.Bold)
128 End Sub ' boldToolStripMenuItem_Click
131 Private Sub italicToolStripMenuItem_Click( _
133 Handles italicToolStripMenuItem.Click
135 italicToolStripMenuItem.Checked = _
138 ' use Xor to toggle italic, keep all other styles
139 displayLabel.Font = New Font(displayLabel.Font.FontFamily, 14, _
140 displayLabel.Font.Style Xor FontStyle.Italic)
141 End Sub ' italicToolStripMenuItem_Click
FirstDayOfWeek
Sets which day of the week is the first for each week.
MaxDate
MaxSelectionCount
The maximum number of dates that can b e selected
at once.
MonthlyBoldedDates
An array of dates that will displayed in bold in the
calendar.
SelectionEnd
SelectionRange
SelectionStart
Common MonthCalendar Event
DateTimePicker
CalendarMonth-
Background
CustomFormat
Sets the custom format string for the user’s options.
Date
MaxDate
MinDate
DateTimePicker
ShowUpDown
Used to indicate that the control should have up and down
Buttons.
TimeOfDay
Common DateTimePicker Event
1 ' Fig. 14.52: DateTimePickerTest.vb
2 ' Using a DateTimePicker to select a drop off date.
3 Public Class DateTimePickerTest
5 Private Sub DateTimePickerTest_Load( ByVal sender As System.Object, _
6 ByVal e As System.EventArgs) Handles MyBase.Load
7 ' user cannot select days before today
8 dropOffDateTimePicker.MinDate = DateTime.Today
9
10 ' user can select days up to one year from now
11 dropOffDateTimePicker.MaxDate = DateTime.Today.AddYears( 1)
12 End Sub ' DateTimePickerTest_Load
17 Handles dropOffDateTimePicker.ValueChanged
20
21 ' add an extra day when items are dropped off Friday -Sunday
22 If dropOffDate.DayOfWeek = DayOfWeek.Friday Or _
23 dropOffDate.DayOfWeek = DayOfWeek.Saturday Or _
24 dropOffDate.DayOfWeek = DayOfWeek.Sunday Then
26 outputLabel.Text = dropOffDate.AddDays( 3).ToLongDateString()
28 outputLabel.Text = dropOffDate.AddDays(2).ToLongDateString()
29 End If
LinkArea
Specifies which portion of the text is part of the link.
LinkBehavior
LinkColor
Specifies the original color of all links before they have been
visited. The default color is set by the system, but is usually blue.
LinkVisited
If True, the link appears as though it has been visited.
Text
UseMnemonic
If True, the & character can be used to create a shortcut.
VisitedLinkColor
Common Event (event argument type is LinkLabelLinkClickedEventArgs )
LinkClicked
1 ' Fig. 14.55: LinkLabelTestForm.vb
3
7 System.Object, ByVal e As LinkLabelLinkClickedEventArgs) _
8 Handles cDriveLinkLabel.LinkClicked
11 Process.Start("C:\")
15 Private Sub deitelLinkLabel_LinkClicked( ByVal sender As _
16 System.Object, ByVal e As LinkLabelLinkClickedEventArgs) _
17 Handles deitelLinkLabel.Li nkClicked
20 Process.Start("IExplore", "http://www.deitel.com")
24 Private Sub notepadLinkLabel_LinkClicked(ByVal sender As _
25 System.Object, ByVal e As LinkLabelLinkClickedEventArgs) _
26 Handles notepadLinkLabel.LinkClicked
29 Process.Start("notepad")
MultiColumn
Indicates whether the ListBox can break a list into multiple
columns.
SelectedIndex
Returns the index of the selected item, or -1 if no items have
been selected.
items.
SelectedItem
ListBox properties,
SelectionMode
Determines the number of items that can be selected and the
means through which multiple items can be s elected.
Sorted
Common Methods
GetSelected
Returns True if the item at the argument’s index is selected.
Common Event
1 ' Fig. 14.59: ListBoxTestForm.vb
3 Public Class ListBoxTestForm
4 ' add to displayListBox the item the user enters in inputTextBox,
5 ' then clear inputTextBox
8
13 ' remove an item from displayListBox if one is selected
14 Private Sub removeButton_Click( ByVal sender As System.Object, _
15 ByVal e As System.EventArgs) Handles removeButton.Click
16
18 If displayListBox.SelectedIndex <> -1 Then
19 displayListBox.Items.RemoveAt(displayListBox.SelectedIndex)
26
33
and an event Description
Common Properties (All the ListBox properties, methods and events are inherited by
CheckedListBox.)
CheckedItems
CheckedIndices
CheckOnClick
SelectionMode
Common Method
CheckedListBox
ItemCheck
ItemCheckEventArgs Properties
Index
NewValue
1 ' Fig. 14.61: CheckedListBoxTestForm.vb
2 ' Using the checked ListBox to add items to a display ListBox
3 Public Class CheckedListBoxTestForm
4 ' add an item to or remove an item from lstDisplay
5 Private Sub itemCheckedListBox_ItemCheck( _
7 Handles itemCheckedListBox.ItemCheck
11
12 ' if the selected item is checked add it to displayListBox;
13 ' otherwise, remove it from displayListBox
14 If e.NewValue = CheckState.Checked Then
15 displayListBox.Items.Add(item)
16 Else
17 displayListBox.Items.Remove(item)
Items
MaxDropDownItems
Specifies the maximum number of items that the drop -down
list can display.
SelectedItem
Sorted
Common Event
1 ' Fig. 14.64: ComboBoxTest.vb
3 Public Class ComboBoxTest
4 ' get index of selected shape, then draw the shape
5 Private Sub imageComboBox_SelectedIndexChanged( _
7 Handles imageComboBox.SelectedIndexChanged
9 Dim myGraphics As Graphics = MyBase.CreateGraphics()
10
13
15 Dim mySolidBrush As SolidBrush = New SolidBrush(Color.DarkRed)
16
18 myGraphics.Clear( Color.White)
21 Select Case imageComboBox.SelectedIndex
23 myGraphics.DrawEllipse(myPen, 50, 50, 150, 150)
24 Case 1 ' case Rectangle is selected
25 myGraphics.DrawRectangle(myPen, 50, 50, 150, 150)
26 Case 2 ' case Ellipse is selected
27 myGraphics.DrawEllipse(myPen, 50, 85, 150, 115)
28 Case 3 ' case Pie is selected
29 myGraphics.DrawPie(myPen, 50, 50, 150, 150, 0, 45)
30 Case 4 ' case Filled Circle is selected
31 myGraphics.FillEllipse(mySolidBrush, 50, 50, 150, 150)
32 Case 5 ' case Filled Rectangle is selected
33 myGraphics.FillRectangle(mySolidBrush, 50, 50, 150, 150)
34 Case 6 ' case Filled Ellipse is selected
35 myGraphics.FillEllipse(mySolidBrush, 50, 85, 150, 115)
36 Case 7 ' case Filled Pie is selected
37 myGraphics.FillPie(mySoli dBrush, 50, 50, 150, 150, 0, 45)
38 End Select
41 End Sub ' imageComboBox_SelectedIndexChanged
42 End Class ' ComboBoxTest
ImageList
Nodes
SelectedNode
AfterSelect
TreeNode properties
FirstNode
FullPath
Indicates the path of the node, starting at the root.
ImageIndex
Specifies the index of the image shown when the node is deselected.
LastNode
NextNode
Collection of the current node’s child TreeNodes with methods
Add, Clear and Remove.
PrevNode
SelectedImageIndex
Specifies the index of the image to use when the node is selected.
Text
Common Methods
GetNodeCount
1 ' Fig. 14.69: TreeViewDirectoryStructure.vb
3 Imports System.IO
7 Private Sub enterButton_Click(ByVal sender As System.Object, _
8 ByVal e As System.EventArgs) Handles enterButton.Click
9
11
12 ' if the directory specified by the user exists, fill in t he
13 ' TreeView; otherwise, display an error message
14 If (Directory.Exists(inputTextBox.Text )) Then
16 directoryTreeView.Nodes.Add(inputTextBox.Text)
21 MessageBox.Show(inputTextBox.Text & " could not be found." , _
22 "Directory Not Found" , MessageBoxButtons.OK , _
23 MessageBoxIcon.Error )
28 Private Sub PopulateTreeView( _
31 Dim directoryArray As String() = _
32 Directory.GetDirectories(directoryValue)
35 Try
36 ' check to s ee if any subdirectories are present
37 If directoryArray.Length <> 0 Then
38 ' for every subdirectory, create new TreeNode,
39 ' add as a child of current node and recursively
40 ' populate child nodes with subdirectories
41 For Each directory In directoryArray
42 ' obtain last part of path name from the full path name
43 ' by calling the GetFileNameWithoutExtension method of the
44 ' Path class
46 Path.GetFileNameWithoutExtension(directory)
49 Dim myNode As TreeNode = New TreeNode(directoryName)
50
52 parentNode.Nodes.Add(myNode)
55 PopulateTreeView(directory, myNode)
59 parentNode.Nodes.Add( "Access denied")
LargeImageList
display.
Items
MultiSelect
ListView properties
SmallImageList
display.
View
1 ' Fig. 14.72: ListViewTestForm.vb
3 Imports System.IO
8
10 ' (i.e., the one from which the application is executed)
11 Private Sub ListViewTest_Load( ByVal sender As Object, _
12 ByVal e As System.EventArgs) Handles Me.Load
13
16 Dim folderImageResource = My.Resources.ResourceManager.GetObject( _
19 "file")
21 ' convert picture resources to Images and load into PictureBoxes
22 fileFolderImageList.Images.Add( CType(folderImageResource, Image))
23 fileFolderImageList.Images.Add( CType(fileImageResource, Image))
26 LoadFilesInDirectory(currentDirectory)
29
30 ' browse directory user clicked or go up one l evel
31 Private Sub browserListView_Click( ByVal sender As System.Object, _
32 ByVal e As System.EventArgs) Handles browserListView.Click
33 ' ensure an item is selected
34 If browserListView.SelectedItems.Count <> 0 Then
35 ' if first item selected, go up one level
36 If browserListView.Items( 0).Selected Then
37 ' create DirectoryInfo object for directory
38 Dim directoryObject As DirectoryInfo = _
39 New DirectoryInfo(currentDirectory)
42 If directoryObject.Parent IsNot Nothing Then
43 LoadFilesInDirectory(directoryObject.Parent.FullName)
47 ' directory or file chosen
48 Dim chosen As String = browserListView.SelectedItems( 0).Text
49
51 If Directory.Exists( _
65 Private Sub LoadFilesInDirectory( _
67 ' load directory information and display
68 Try
70 browserListView.Items.Clear()
72
76 New DirectoryInfo(currentDirectory)
79 Dim directoryArray As DirectoryInfo() = _
80 newCurrentDirectory.GetDirectories()
82
85 ' add directory to ListView
86 Dim newDirectoryItem As ListViewItem = _
87 browserListView.Items.Add(dir.Name)
90 Next
94 ' add file to ListView
95 Dim newFileItem As ListViewItem = _
96 browserListView.Items.Add(file.Name)
99 Next
101 MessageBox.Show( "Warning: Some files may not be " & _
102 "visible due to permission settin gs", _
103 "Attention", 0, MessageBoxIcon.Warning )
ItemSize
SelectedIndex
SelectedTab
TabPages
Common Event
is selected).
3 Public Class UsingTabsForm
5 Private Sub blackRadioButton_CheckedChanged( _
7 Handles blackRadioButton.CheckedChanged
10 End Sub ' blackRadioButton_CheckedChanged
13 Private Sub redRadioButton_CheckedChanged( _
15 Handles redRadioButton.CheckedChanged
18 End Sub ' redRadioButton_CheckedChanged
21 Private Sub greenRadioButton_Ch