GUI ProgrammingGUI ProgrammingObjectives
In this chapter you will learn:•Design principles of graphical user interfaces (GUIs).•How to create graphical user interfaces.•How to process events that are generated by user interactions with GUI controls.•The namespaces that contain the classes for graphical user interface controls and event handling.•How to create and manipulate controls.•How to process mouse and keyboard events.
Visual Basic 2005
2GUI PROGRAMMING
OverviewOverview
A graphical user interface (GUI) allows a user to interact visually with a program
A GUI (pronounced "GOO-ee") gives a program a distinctive look-and-feel
Consistent user interfaces enable a user to learn new applications faster because the applications have the same look-and-feel
Visual Basic 2005
GUI Programming
3GUI PROGRAMMING
OverviewOverview
GUI controls in an MS Word window
Menu
Toolbar
Scrollbar
Workarea
Visual Basic 2005
4GUI PROGRAMMING
GUI Programming
OverviewOverview
Some basic GUI controls
Control Description
Label Displays images or uneditable text.
TextBox Enables the user to enter data via the keyboard. Also can be used to display editable or uneditable text.
Button Triggers an event when clicked with the mouse.
CheckBox Specifies an option that can be selected (checked) or unselected (not checked).
ComboBox Provides a drop-down list of items from which the user can make a selection either by clicking an item in the list or by typing in a box.
ListBox Provides a list of items from which the user can make a selection by clicking an item in the list. Multiple elements can be selected.
Panel A container in which controls can be placed and organized.
NumericUpDown Enables the user to select from a range of numeric input values.
Visual Basic 2005
5GUI PROGRAMMING
GUI Programming
Windows FormsWindows Forms
Windows Forms are used to create the GUIs for programs
A Form is a graphical element that appears on your computer's desktop
Visual Basic 2005
Form in design view
6GUI PROGRAMMING
GUI Programming
Windows FormsWindows Forms
A component is an instance of a class that implements the IComponent interface, which defines the behaviors that components must implement, such as how the component is loaded
A control, such as a Button or Label, has a graphical representation at runtime
Visual Basic 2005
7GUI PROGRAMMING
GUI Programming
Windows FormsWindows Forms
Components and controls for Windows Forms
Visual Basic 2005
Form controls
Control categories
8GUI PROGRAMMING
GUI Programming
Windows FormsWindows Forms
Common Form properties, methods and an event
Visual Basic 2005
9GUI PROGRAMMING
GUI Programming
Form properties, methods and an
event
Description
Common Properties
AcceptButton Button that is clicked when Enter is pressed.
AutoScroll Boolean value that allows or disallows scrollbars when needed.
CancelButton Button that is clicked when the Escape key is pressed.
FormBorderStyle Border style for the Form (e.g., none, single, three-dimensional).
Font Font of text displayed on the Form, and the default font for controls added to the Form.
Text Text in the Form's title bar.
Common Methods
Close Closes a Form and releases all resources, such as the memory used for the Form's controls and components. A closed Form cannot be reopened.
Hide Hides a Form, but does not destroy the Form or release its resources.
Show Displays a hidden Form.
Common Event
Load Occurs before a Form is displayed to the user. The handler for this event is displayed in the Visual Studio editor when you double click the Form in the Visual Studio designer.
Event HandlingEvent Handling
Normally, a user interacts with an application's GUI to indicate the tasks that the application should perform
GUIs are event drivenWhen the user interacts with a GUI
component, the interaction known as an event drives the program to perform a task
Visual Basic 2005
10GUI PROGRAMMING
GUI Programming
Event HandlingEvent Handling
Simple event-handling example using visual programming
GUI PROGRAMMING 11
Visual Basic 2005
' Using Visual Studio to create event handlers. Public Class FrmSimpleEventExample ' event handler for btnClickMe's Click event Private Sub btnClickMe_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnClickMe.Click
MessageBox.Show("Button was clicked.") End Sub ' btnClickMe_Click End Class ' FrmSimpleEventExample
' Using Visual Studio to create event handlers. Public Class FrmSimpleEventExample ' event handler for btnClickMe's Click event Private Sub btnClickMe_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnClickMe.Click
MessageBox.Show("Button was clicked.") End Sub ' btnClickMe_Click End Class ' FrmSimpleEventExample
Event procedure
GUI Programming
Event HandlingEvent Handling
Simple event-handling example output
GUI PROGRAMMING 12
Visual Basic 2005
GUI Programming
Event HandlingEvent Handling
A look at the Visual Studio generated code
GUI PROGRAMMING 13
Visual Basic 2005
Dispose event
procedure
GUI Programming
Event HandlingEvent Handling
The control that generates an event is known as the event sender
An event-handling method known as the event receiver responds to a particular event that a control generates
When the event occurs, the event sender calls its event receiver to perform a task
GUI PROGRAMMING 14
Visual Basic 2005
GUI Programming
Event HandlingEvent Handling
Event handlers are connected to a control's events via special objects called delegates
A delegate object holds a reference to a method
The method's signature must match the signature specified by the delegate type's declaration
GUI controls have predefined delegates that correspond to every event they can generate
GUI PROGRAMMING 15
Visual Basic 2005
GUI Programming
Event HandlingEvent Handling
For example, the delegate for a Button's click event is of type EventHandler (namespace System)
If you look at this type in the online help documentation, you will see that it is declared as follows:
GUI PROGRAMMING 16
Visual Basic 2005
Public Delegate Sub EventHandler(sender As Object, e As EventArgs) Public Delegate Sub EventHandler(sender As Object, e As EventArgs)
GUI Programming
Event HandlingEvent Handling
An event sender uses a delegate object like a method call
The event sender can simply "call" the appropriate delegate when an event occurs
The delegate's job is to invoke the appropriate event-handler method
To enable the btnClickMe_Click method to be called when the user clicks the Button, Visual Basic inserts the clause:
GUI PROGRAMMING 17
Visual Basic 2005
Handles controlName.eventNameHandles controlName.eventName
GUI Programming
Event HandlingEvent Handling
Using the Properties Window to Create Event Handlers
GUI PROGRAMMING 18
Visual Basic 2005
Properties icon Events icon
Selected event
GUI Programming
Control Properties and LayoutControl Properties and Layout
Controls derive from class Control (namespace System.Windows.Forms)
GUI PROGRAMMING 19
Visual Basic 2005
Visual Basic controls
GUI Programming
Control Properties and LayoutControl Properties and Layout
Class Control properties and methods
GUI PROGRAMMING 20
Visual Basic 2005
Class Control Properties
Description
BackColor The control's background color.
BackgroundImage The control's background image.
Enabled Specifies whether the control is enabled (i.e., whether the user can interact with it). Typically, portions of a disabled control appear "grayed out" as a visual indication to the user that the control is disabled.
Focused Indicates whether the control has the focus.
Font The Font used to display the control's text.
ForeColor The control's foreground color. This usually determines the color of the text in the Text property.
TabIndex The tab order of the control. When the Tab key is pressed, the focus transfers between controls based on the tab order. You can set this order.
TabStop If True, then a user can give focus to this control via the Tab key.
Text The text associated with the control. The location and appearance of the text vary depending on the type of control.
Visible Indicates whether the control is visible.
GUI Programming
Control Properties and LayoutControl Properties and Layout
Class Control properties and methods
GUI PROGRAMMING 21
Class Control Methods
Description
Focus Acquires the focus.
Hide Hides the control (sets the Visible property to False).
Show Shows the control (sets the Visible property to True).
Visual Basic 2005
GUI Programming
Control Properties and LayoutControl Properties and Layout
Manipulating the Anchor property of a control
GUI PROGRAMMING 22
Anchor property
Anchoring window
Button is anchored to bottom right. It will maintain a constant distance to the bottom right corner of the
Form when resized
Visual Basic 2005
GUI Programming
Control Properties and LayoutControl Properties and Layout
Control layout properties
GUI PROGRAMMING 23
Control Layout Properties
Description
Anchor Causes a control to remain at a fixed distance from the side(s) of the container even when the container is resized.
Dock Allows a control to span one side of its container or to fill the entire container.
Padding Sets the space between a container's edges and docked controls. The default is 0, causing the control to appear flush with the container's sides.
Location Specifies the location (as a set of coordinates) of the upper-left corner of the control, in relation to its container.
Size Specifies the size of the control in pixels as a Size object, which has properties Width and Height.
MinimumSize, MaximumSize
Indicate the minimum and maximum sizes of a Control, respectively.
Visual Basic 2005
GUI Programming
LabelLabels, s, TextBoxTextBoxes and es and ButtonButtonss
Labels provide text information (as well as optional images) and are defined with class Label (a derived class of Control)
A Label displays text that the user cannot directly modify
A Label's text can be changed programmatically by modifying the Label's Text property
GUI PROGRAMMING 24
Visual Basic 2005
GUI Programming
LabelLabels, s, TextBoxTextBoxes and es and ButtonButtonss
Common Label properties
GUI PROGRAMMING 25
Label Properties Description
Font The font of the text on the Label.
Text The text on the Label.
TextAlign The alignment of the Label's text on the controlhorizontally (left, center or right) and vertically (top, middle or bottom).
Label control
Visual Basic 2005
GUI Programming
LabelLabels, s, TextBoxTextBoxes and es and ButtonButtonss
A textbox (class TextBox) is an area in which text can be displayed by a program or the user can type text via the keyboard
GUI PROGRAMMING 26
TextBox control
Visual Basic 2005
GUI Programming
LabelLabels, s, TextBoxTextBoxes and es and ButtonButtonss
TextBox properties and an event
GUI PROGRAMMING 27
Label Properties Description
Common Properties
AcceptsReturn If true in a multiline TextBox, pressing Enter in the TextBox creates a new line. If False, pressing Enter is the same as pressing the default Button on the Form. The default Button is the one assigned to a Form's AcceptButton property.
Multiline If true, the TextBox can span multiple lines. The default value is False.
PasswordChar When this property is set to a character, the TextBox becomes a password box, and the specified character masks each character the user types. If no character is specified, the TextBox displays the typed text.
ReadOnly If TRue, the TextBox has a gray background, and its text cannot be edited. The default value is False.
ScrollBars For multiline textboxes, this property indicates which scrollbars appear (None, Horizontal, Vertical or Both).
Text The TextBox's text content.
Common Event
TextChanged Generated when the text changes in a TextBox (i.e., when the user adds or deletes characters). When you double click the TextBox control in Design mode, an empty event handler for this event is generated.
Visual Basic 2005
GUI Programming
LabelLabels, s, TextBoxTextBoxes and es and ButtonButtonss
A button is a control that the user clicks to trigger a specific action or to select an option in a program
A program can use various button types, such as checkboxes and radio buttons
All the button classes derive from ButtonBase (namespace System.Windows.Forms)
GUI PROGRAMMING 28
Visual Basic 2005
GUI Programming
LabelLabels, s, TextBoxTextBoxes and es and ButtonButtonss
Button properties and an event
GUI PROGRAMMING 29
Button Properties Description
Common Properties
Text Specifies the text displayed on the Button face.
FlatStyle Modifies a Button's appearance attribute Flat (for the Button to display without a three-dimensional appearance), Popup (for the Button to appear flat until the user moves the mouse pointer over the Button), Standard (three-dimensional) and System, where the Button's appearance is controlled by the operating system. The default value is Standard.
Common Event
Click Generated when the user clicks the Button. When you double click a Button in design view, an empty event handler for this event is created.
Visual Basic 2005
GUI Programming
LabelLabels, s, TextBoxTextBoxes and es and ButtonButtonss
Program to display hidden text in a password box
GUI PROGRAMMING 30
' Using a TextBox, Label and Button to display ' the hidden text in a password TextBox. Public Class FrmLabelTextBoxButtonTest ' event handler for btnDisplayPassword's Click event Private Sub btnDisplayPassword_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnDisplayPassword.Click
' display the text that the user typed lblDisplayPassword.Text = txtInputPassword.Text
End Sub ' btnDisplayPassword_Click End Class ' FrmLabelTextBoxButtonTest
' Using a TextBox, Label and Button to display ' the hidden text in a password TextBox. Public Class FrmLabelTextBoxButtonTest ' event handler for btnDisplayPassword's Click event Private Sub btnDisplayPassword_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnDisplayPassword.Click
' display the text that the user typed lblDisplayPassword.Text = txtInputPassword.Text
End Sub ' btnDisplayPassword_Click End Class ' FrmLabelTextBoxButtonTest
Visual Basic 2005
GUI Programming
LabelLabels, s, TextBoxTextBoxes and es and ButtonButtonss
Program to display hidden text in a password box
GUI PROGRAMMING 31
Visual Basic 2005
GUI Programming
GroupBoxGroupBoxes and es and PanelPanelss
GroupBoxes and Panels arrange controls on a GUI
GroupBoxes and Panels are typically used to group several controls of similar functionality or several controls that are related in a GUI
All of the controls in a GroupBox or Panel move together when the GroupBox or Panel is moved
GUI PROGRAMMING 32
Visual Basic 2005
GUI Programming
GroupBoxGroupBoxes and es and PanelPanelss
The primary difference between these two controls is that GroupBoxes can display a caption (i.e., text) and do not include scrollbars, whereas Panels can include scrollbars and do not include a caption
GUI PROGRAMMING 33
GroupBox control
Panel control
Visual Basic 2005
GUI Programming
CheckBoxCheckBoxes and es and RadioButtonRadioButtonss
Visual Basic has two types of state buttons that can be in the on/off or true/false states: CheckBoxes and RadioButtons
GUI PROGRAMMING 34
Visual Basic 2005
CheckBox control
RadioButton control
GUI Programming
CheckBoxCheckBoxes and es and RadioButtonRadioButtonss
Using CheckBoxes to change font styles
GUI PROGRAMMING 35
Visual Basic 2005
Public Class FrmCheckBoxTest
Private Sub chkBold_CheckedChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles chkBold.CheckedChanged lblOutput.Font = New Font(lblOutput.Font.Name, lblOutput.Font.Size, _ lblOutput.Font.Style Xor FontStyle.Bold) End Sub
Private Sub chkItalic_CheckedChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles chkItalic.CheckedChanged lblOutput.Font = New Font(lblOutput.Font.Name, lblOutput.Font.Size, _ lblOutput.Font.Style Xor FontStyle.Italic) End Sub
End Class
Public Class FrmCheckBoxTest
Private Sub chkBold_CheckedChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles chkBold.CheckedChanged lblOutput.Font = New Font(lblOutput.Font.Name, lblOutput.Font.Size, _ lblOutput.Font.Style Xor FontStyle.Bold) End Sub
Private Sub chkItalic_CheckedChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles chkItalic.CheckedChanged lblOutput.Font = New Font(lblOutput.Font.Name, lblOutput.Font.Size, _ lblOutput.Font.Style Xor FontStyle.Italic) End Sub
End Class
GUI Programming
CheckBoxCheckBoxes and es and RadioButtonRadioButtonss
Using CheckBoxes to change font styles
GUI PROGRAMMING 36
Visual Basic 2005
GUI Programming
PictureBoxPictureBoxeses
A PictureBox displays an imageThe image can be one of several formats,
such as bitmap, GIF (Graphics Interchange Format) and JPEG
GUI PROGRAMMING 37
Visual Basic 2005
PictureBox control
GUI Programming
PictureBoxPictureBoxeses
PictureBox proerties and an event.
GUI PROGRAMMING 38
Visual Basic 2005
PictureBox Properties
Description
Common Properties
Image Sets the image to display in the PictureBox.
SizeMode Enumeration that controls image sizing and positioning. Values are Normal (default), StretchImage, AutoSize and CenterImage. Normal places the image in the top-left corner of the PictureBox; CenterImage puts the image in the middle. Both options truncate the image if it is too large. StretchImage resizes the image to fit in the PictureBox. AutoSize resizes the PictureBox to fit the image.
Common Event
Click Occurs when the user clicks the control. Double clicking this control design mode generates an empty event handler for this event.
GUI Programming
PictureBoxPictureBoxeses
Using a PictureBox to display images
GUI PROGRAMMING 39
Visual Basic 2005
Imports System.IO
Public Class FrmPictureBoxTest ' determines which image is displayed Private imageNum As Integer = -1
' change image whenever Next Button is clicked Private Sub btnNext_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnNext.Click
imageNum = (imageNum + 1) Mod 3 ' imageNum cycles from 0 to 2
' create Image object from file, display in PicutreBox picImage.Image = Image.FromFile(Directory.GetCurrentDirectory() & _ "\images\image" & imageNum & ".bmp") End Sub ' btnNext_Click
End Class
Imports System.IO
Public Class FrmPictureBoxTest ' determines which image is displayed Private imageNum As Integer = -1
' change image whenever Next Button is clicked Private Sub btnNext_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnNext.Click
imageNum = (imageNum + 1) Mod 3 ' imageNum cycles from 0 to 2
' create Image object from file, display in PicutreBox picImage.Image = Image.FromFile(Directory.GetCurrentDirectory() & _ "\images\image" & imageNum & ".bmp") End Sub ' btnNext_Click
End Class
GUI Programming
PictureBoxPictureBoxeses
Using a PictureBox to display images
GUI PROGRAMMING 40
Visual Basic 2005
Clicking the Next Image button will display another image
GUI Programming
Mouse Event HandlingMouse Event Handling
Mouse events can be handled for any control that derives from class System.Windows.Forms.Control
For most mouse events, information about the event is passed to the event-handling method through an object of class MouseEventArgs, and the delegate used to create the mouse-event handlers is MouseEventHandler
GUI PROGRAMMING 41
Visual Basic 2005
GUI Programming
Mouse Event HandlingMouse Event Handling
Mouse events and event arguments
GUI PROGRAMMING 42
Visual Basic 2005
Mouse events and arguments
Description
Mouse Events with Event Argument of Type EventArgs
MouseEnter Occurs when the mouse cursor enters the control's boundaries.
MouseLeave Occurs when the mouse cursor leaves the control's boundaries.
Mouse Events with Event Argument of Type MouseEventArgs
MouseDown Occurs when a mouse button is pressed while the mouse cursor is within a control's boundaries.
MouseHover Occurs when the mouse cursor hovers within the control's boundaries.
MouseMove Occurs when the mouse cursor is moved while in the control's boundaries.
MouseUp Occurs when a mouse button is released when the cursor is within the control's boundaries.
Class MouseEventArgs Properties
Button Specifies which mouse button was pressed (Left, Right, Middle or none).
Clicks The number of times the mouse button was clicked.
X The x-coordinate within the control where the event occurred.
Y The y-coordinate within the control where the event occurred.
GUI Programming
Mouse Event HandlingMouse Event Handling
Using the mouse to draw on a Form
GUI PROGRAMMING 43
Visual Basic 2005
' Using the mouse to draw on a Form.Public Class FrmPainter
Private shouldPaint As Boolean = False ' determines whether to paint
' should paint when mouse button is pressed down Private Sub FrmPainter_MouseDown(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) _ Handles MyBase.MouseDown shouldPaint = True End Sub ' FrmPainter_MouseDown
' stop painting when mouse button is released Private Sub FrmPainter_MouseUp(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) _ Handles MyBase.MouseUp shouldPaint = False End Sub ' FrmPainter_MouseUp
... continued
' Using the mouse to draw on a Form.Public Class FrmPainter
Private shouldPaint As Boolean = False ' determines whether to paint
' should paint when mouse button is pressed down Private Sub FrmPainter_MouseDown(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) _ Handles MyBase.MouseDown shouldPaint = True End Sub ' FrmPainter_MouseDown
' stop painting when mouse button is released Private Sub FrmPainter_MouseUp(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) _ Handles MyBase.MouseUp shouldPaint = False End Sub ' FrmPainter_MouseUp
... continued
GUI Programming
Mouse Event HandlingMouse Event Handling
Using the mouse to draw on a Form
GUI PROGRAMMING 44
Visual Basic 2005
' draw circle whenever mouse moves with its button held down Private Sub FrmPainter_MouseMove(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) _ Handles MyBase.MouseMove ' check if mouse button is being pressed If (shouldPaint) Then ' draw a circle where the mouse pointer is present Dim g As Graphics = CreateGraphics()
g.FillEllipse(New SolidBrush(Color.BlueViolet), e.X, e.Y, 4, 4) g.Dispose() End If End Sub ' FrmPainter_MouseMove
End Class
' draw circle whenever mouse moves with its button held down Private Sub FrmPainter_MouseMove(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) _ Handles MyBase.MouseMove ' check if mouse button is being pressed If (shouldPaint) Then ' draw a circle where the mouse pointer is present Dim g As Graphics = CreateGraphics()
g.FillEllipse(New SolidBrush(Color.BlueViolet), e.X, e.Y, 4, 4) g.Dispose() End If End Sub ' FrmPainter_MouseMove
End Class
GUI Programming
Mouse Event HandlingMouse Event Handling
Using the mouse to draw on a Form
GUI PROGRAMMING 45
Visual Basic 2005
GUI Programming
Keyboard-Event HandlingKeyboard-Event Handling
Key events occur when keyboard keys are pressed and released
Such events can be handled for any control that inherits from System.Windows.Forms.Control
There are three key events: KeyPress, KeyUp and KeyDown
GUI PROGRAMMING 46
Visual Basic 2005
GUI Programming
Keyboard-Event HandlingKeyboard-Event Handling
Keyboard events and event arguments
GUI PROGRAMMING 47
Visual Basic 2005
Keyboard events and arguments
Description
Key Events with Event Arguments of Type KeyEventArgs
KeyDown Generated when a key is initially pressed.
KeyUp Generated when a key is released.
Key Event with Event Argument of Type KeyPressEventArgs
KeyPress Generated when a key is pressed.
Class KeyPressEventArgs Properties
KeyChar Returns the ASCII character for the key pressed.
Handled Indicates whether the KeyPress event was handled.
GUI Programming
Keyboard-Event HandlingKeyboard-Event Handling
Keyboard events and event arguments
GUI PROGRAMMING 48
Visual Basic 2005
Keyboard events and arguments
Description
Class KeyEventArgs Properties
Alt Indicates whether the Alt key was pressed.
Control Indicates whether the Ctrl key was pressed.
Shift Indicates whether the Shift key was pressed.
Handled Indicates whether the event was handled.
KeyCode Returns the key code for the key as a value from the Keys enumeration. This does not include modifier-key information. It is used to test for a specific key.
KeyData Returns the key code for a key combined with modifier information as a Keys value. This property contains all the information about the pressed key.
KeyValue Returns the key code as an int, rather than as a value from the Keys enumeration. This property is used to obtain a numeric representation of the pressed key. The int value is known as a Windows virtual key code.
Modifiers Returns a Keys value indicating any pressed modifier keys (Alt, Ctrl and Shift). This property is used to determine modifier-key information only.
GUI Programming
Keyboard-Event HandlingKeyboard-Event Handling
Demonstrating keyboard events
GUI PROGRAMMING 49
Visual Basic 2005
Public Class FrmKeyDemo ' display the character pressed using KeyChar Private Sub FrmKeyDemo_KeyPress(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.KeyPressEventArgs) _ Handles MyBase.KeyPress
lblChar.Text = "Key pressed: " & e.KeyChar End Sub ' FrmKeyDemo_KeyPress
' clear Labels when keys are released Private Sub FrmKeyDemo_KeyUp(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyUp
lblChar.Text = "" lblKeyInfo.Text = "" End Sub ' FrmKeyDemo_KeyUp
... continued
Public Class FrmKeyDemo ' display the character pressed using KeyChar Private Sub FrmKeyDemo_KeyPress(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.KeyPressEventArgs) _ Handles MyBase.KeyPress
lblChar.Text = "Key pressed: " & e.KeyChar End Sub ' FrmKeyDemo_KeyPress
' clear Labels when keys are released Private Sub FrmKeyDemo_KeyUp(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyUp
lblChar.Text = "" lblKeyInfo.Text = "" End Sub ' FrmKeyDemo_KeyUp
... continued
GUI Programming
Keyboard-Event HandlingKeyboard-Event Handling
Demonstrating keyboard events
GUI PROGRAMMING 50
Visual Basic 2005
' display modifier keys, key code, key data and key value Private Sub FrmKeyDemo_KeyDown(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.KeyEventArgs) _ Handles MyBase.KeyDown
If e.Alt Then ' key is Alt lblKeyInfo.Text = "Alt: Yes" & vbCrLf Else ' key is not Alt lblKeyInfo.Text = "Alt: No" & vbCrLf End If
If e.Shift Then ' key is Shift lblKeyInfo.Text &= "Shift: Yes" & vbCrLf Else ' key is not Shift lblKeyInfo.Text &= "Shift: No" & vbCrLf End If
If e.Control Then ' key is Control lblKeyInfo.Text &= "Control: Yes" & vbCrLf Else ' key is not Control lblKeyInfo.Text &= "Control: No" & vbCrLf End If
' diplay key code, key data and key value lblKeyInfo.Text &= "KeyCode: " & e.KeyCode.ToString() & vbCrLf & _ "KeyData: " & e.KeyData.ToString() & vbCrLf & _ "KeyValue: " & e.KeyValue.ToString() End Sub ' FrmKeyDemo_KeyDownEnd Class
' display modifier keys, key code, key data and key value Private Sub FrmKeyDemo_KeyDown(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.KeyEventArgs) _ Handles MyBase.KeyDown
If e.Alt Then ' key is Alt lblKeyInfo.Text = "Alt: Yes" & vbCrLf Else ' key is not Alt lblKeyInfo.Text = "Alt: No" & vbCrLf End If
If e.Shift Then ' key is Shift lblKeyInfo.Text &= "Shift: Yes" & vbCrLf Else ' key is not Shift lblKeyInfo.Text &= "Shift: No" & vbCrLf End If
If e.Control Then ' key is Control lblKeyInfo.Text &= "Control: Yes" & vbCrLf Else ' key is not Control lblKeyInfo.Text &= "Control: No" & vbCrLf End If
' diplay key code, key data and key value lblKeyInfo.Text &= "KeyCode: " & e.KeyCode.ToString() & vbCrLf & _ "KeyData: " & e.KeyData.ToString() & vbCrLf & _ "KeyValue: " & e.KeyValue.ToString() End Sub ' FrmKeyDemo_KeyDownEnd Class
GUI Programming
Keyboard-Event HandlingKeyboard-Event Handling
Demonstrating keyboard events
GUI PROGRAMMING 51
No keys are pressed yet
User pressed ‘A’ from
keyboard
User pressed Alt+‘B’ from
keyboard
Visual Basic 2005
GUI Programming
User-Defined ControlsUser-Defined Controls
The .NET Framework allows you to create custom controls
These custom controls appear in the user's Toolbox and can be added to Forms, Panels or GroupBoxes in the same way that we add Buttons, Labels and other predefined controls
The simplest way to create a custom control is to derive a class from an existing control, such as a Label
GUI PROGRAMMING 52
GUI Programming
User-Defined ControlsUser-Defined Controls
Creating user controls
GUI PROGRAMMING 53
User control in design view
GUI Programming
User-Defined ControlsUser-Defined Controls
UserControl-defined clock
GUI PROGRAMMING 54
Public Class ClockUserControl ' update label for each clock tick Private Sub tmrClock_Tick(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles tmrClock.Tick ' get current time (Now), convert to String lblDisplay.Text = DateTime.Now.ToLongTimeString() End Sub ' tmrClock_Tick
End Class
Public Class ClockUserControl ' update label for each clock tick Private Sub tmrClock_Tick(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles tmrClock.Tick ' get current time (Now), convert to String lblDisplay.Text = DateTime.Now.ToLongTimeString() End Sub ' tmrClock_Tick
End Class
GUI Programming
User-Defined ControlsUser-Defined Controls
UserControl-defined clock
GUI PROGRAMMING 55
ClockuserControl included in the
form
ClockuserControl tool icon included
in the toolbox
GUI Programming
User-Defined ControlsUser-Defined Controls
UserControl-defined clock
GUI PROGRAMMING 56
ClockUserControl refreshes every
second
GUI Programming
Multiple Document Interface (MDI) Multiple Document Interface (MDI) WindowsWindows
Multiple Document Interfaces (MDIs), allow users to edit multiple documents at once
MDI programs also tend to be more complex
The main application window of an MDI program is called the parent window
Each window inside the application is referred to as a child window
GUI PROGRAMMING 57
Visual Basic 2005
GUI Programming
Multiple Document Interface (MDI) Multiple Document Interface (MDI) WindowsWindows
MDI parent window and MDI child windows
GUI PROGRAMMING 58
Visual Basic 2005
MDI parent
MDI child
GUI Programming
Multiple Document Interface (MDI) Multiple Document Interface (MDI) WindowsWindows
MDI parent and MDI child properties
GUI PROGRAMMING 59
Visual Basic 2005
MDI Form properties,
method and an event
Description
Common MDI Child Properties
IsMdiChild Indicates whether a Form is an MDI child. If true, the Form is an MDI child (read-only property).
MdiParent Specifies the MDI parent Form of the child.
Common MDI Parent Properties
ActiveMdiChild Returns the Form that is the currently active MDI child (return Nothing if no children are active).
IsMdiContainer Indicates whether a Form can be an MDI parent If true, the Form can be an MDI parent. The default value is False.
MdiChildren Returns the MDI children as an array of Forms.
Common Method
LayoutMdi Arranges child forms in an MDI parent Form. The method takes as a parameter an MdiLayout enumeration constant (ArrangeIcons, Cascade, TileHorizontal or TileVertical).
Common Event
MdiChildActivate Generated when an MDI child is closed or activated.
GUI Programming