Module 6: Using Windows Forms
Module 6: Using Windows Forms
Module 6: Using Windows Forms
Windows Forms
Contents
Overview 1
Why Use Windows Forms? 2
Structure of Windows Forms 4
Using Windows Forms 12
Demonstration: Manipulating
Windows Forms 27
Using Controls 28
Demonstration: Implementing
Drag-and-Drop Functionality 42
Windows Forms Inheritance 43
Demonstration: Using Windows Forms
Inheritance 48
Lab 6.1: Creating the Customer Form 49
Review 58
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part
of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted
in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or
for any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, FrontPage, IntelliSense, JScript,
Microsoft Press, Outlook, PowerPoint, Visio, Visual Basic, Visual C++, Visual C#, Visual
InterDev, Visual J#, Visual SourceSafe, Visual Studio, and Windows Media are either registered
trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 6: Using Windows Forms iii
Instructor Notes
Presentation: This module provides students with the knowledge needed to create Microsoft®
120 Minutes Windows®-based applications.
Lab: In the lab, students will continue working with the Cargo system. The
45 Minutes Customer class from Lab 5.1 has been enhanced for students, and a
CustomerList class has been provided to iterate through the customers. The
basic Customer form has been provided, but it requires further development.
After completing this module, students will be able to:
Describe the benefits of Windows Forms.
Use the new properties and methods of Windows Forms.
Write event-handling code.
Use the new controls and control enhancements.
Add and edit menus.
Create a form that inherits from another form.
Required Materials
To teach this module, you need the following materials:
Microsoft PowerPoint® file 2373B_06.ppt
Module 6, “Using Windows Forms”
Lab 6.1, Creating the Customer Form
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
Read the instructor notes and the margin notes for the module.
Practice the demonstrations.
Complete the practice.
Complete the lab.
iv Module 6: Using Windows Forms
Demonstrations
This section provides demonstration procedures that will not fit in the margin
notes or are not appropriate for the student notes.
Using Controls
To examine the frmControls code
1. Open the ControlsDemo.sln solution in the install folder\DemoCode\
Mod06\ControlsDemo\Starter folder.
2. Open the design window for frmControls.vb. The purpose of the form is to
show the effects of the anchor and dock styles to a Button control. Point out
the Anchoring and Docking menus and their menu items. Also, point out
the FlatStyle property of the btnClose button in the Properties window.
3. View the code window for the frmControls.vb form.
4. View the Sub ProcessAnchorMenus procedure and examine the code,
pointing out that multiple menus are being handled by the one procedure.
5. View the Sub ApplyAnchoring procedure and examine the code.
6. View the Sub ApplyDocking procedure and examine the code.
Module 6: Using Windows Forms v
4. Using the Docking menu, test each docking option, beginning with the Top
menu item and finishing with the Fill menu item. Show the effects these
settings have on the Close button.
5. Click the Close button to quit the application.
lblProductName Public
5. Open the modMain.vb file and change the startup form to frmInherited.
Application.Run(New frmInherited( ))
Name btnCall
Text “” (Empty string)
FlatStyle Popup
Image C:\Program Files\Microsoft Visual Studio.NET\Common7\
Graphics\icons\Comm\Phone01.ico
3. Double-click the new button to edit its btnCall_Click event handler, adding
the following line:
MessageBox.Show("Dialing help line.", "Help Line")
Module Strategy
Use the following strategy to present this module:
Why Use Windows Forms?
This lesson shows some of the benefits of using Windows Forms rather than
Microsoft Visual Basic® forms. This lesson provides an overview because
some of these topics are addressed in more detail later in the module. GDI+,
printing support, accessibility, and the extensible object model are not
covered in any more detail in this module. Extensibility will be covered
when user controls are discussed in Module 9, “Developing Components in
Visual Basic .NET,” in Course 2373B, Programming with Microsoft
Visual Basic .NET.
Structure of Windows Forms
This lesson shows how to use the new Windows Forms object model to
create Windows-based applications. Emphasize the object model hierarchy
because it is this object-oriented approach that provides the power of
Windows Forms. Ensure that students are comfortable with the anatomy of
the form code because this may confuse or concern students whose
background is limited to Visual Basic.
The lesson also discusses various form properties, methods, and events, as
well as how to handle those events. Finally, dialog boxes are examined to
point out the subtle differences between Visual Basic .NET dialog boxes
and those of previous versions of the Visual Basic language.
Using Controls
This lesson shows how to use some of the new and enhanced controls in a
Windows Form. Creating menus with the Menu Designer is not explicitly
covered, although you may want to quickly demonstrate the new designer if
students have not already used it. The lesson also examines some of the user
assistance controls and the new technique for drag-and-drop operations.
Windows Form Inheritance
This lesson shows how to use visual inheritance through the Windows
Forms class library. If students are comfortable with the concept of class
inheritance, they will have no trouble extending that knowledge to visual
inheritance. The process for creating base forms and inherited forms is
examined, as are the effects that modification to a base form can have on
those that inherit from it.
Module 6: Using Windows Forms 1
Overview
Topic Objective
To provide an overview of
the module topics and
objectives. Why Use Windows Forms?
Lead-in Structure of Windows Forms
In this module, you will learn
about Visual Basic .NET Using Windows Forms
Windows Forms.
Using Controls
Windows Forms Inheritance
Form
UserControl
ScrollableControl
The ScrollableControl class inherits directly from the Control class and
provides automatic scrolling capabilities for any control that requires scroll
bars.
ContainerControl
The ContainerControl class inherits directly from the ScrollableControl class
and adds tabbing and focus management functionality for controls that can host
other controls.
6 Module 6: Using Windows Forms
Form
The Form class inherits directly from the ContainerControl class and
represents any window displayed in the application. The properties and
methods provided by the Form class allow you to display many different types
of forms, including dialog boxes and multiple-document interface (MDI) forms.
All Windows Forms are derived from this class because it provides the basic
functionality required by forms.
UserControl
The UserControl class also inherits directly from the ContainerControl class
and provides an empty control that you can use to create your own controls by
using the Windows Forms Designer.
The following example shows how to use the Application class to start your
application, keep it running after the first form is closed, and end the
application. You must remember to change the Startup Object property of the
project from the name of a form to Sub Main for this to work.
Sub Main( )
Dim frmFirst as New Form1( )
frmFirst.Show( ) ' Displays the first form
Application.Run( )
' Allows the application to continue after the form is closed
End Sub
Using DoEvents
The Application class also provides the DoEvents method. This method is
similar to the DoEvents function in Visual Basic 6.0, but it is now implemented
as a method of the Application object.
You use this method to allow other messages in the message queue to be
processed during the handling of a single event in your code. By default, when
your form handles an event, it processes all code in that event handler and will
not respond to other events that may be occurring. If you call the DoEvents
method in that code, your application will have a chance to handle these other
events, such as the repainting of a form that has had another window dragged
over it. You will typically use this method within loops to ensure that other
messages are processed.
Warning When you use the DoEvents method, be careful not to re-enter the
same code. This will cause your application to stop responding.
Module 6: Using Windows Forms 9
Class
A form is an instance of a class in Visual Basic .NET, so all the code belonging
to the form is enclosed within a Public Class definition. This structure allows
you to implement visual inheritance by creating forms that inherit from other
forms.
Inherits System.Windows.Forms.Form
Forms inherit from the System.Windows.Forms.Form class. If you create a
form in Visual Studio .NET, this inheritance is automatic, but if you create
forms elsewhere, you must manually add the Inherits statement. This gives you
the standard functionality of a form but allows you to override methods or
properties as required.
Module 6: Using Windows Forms 11
Constructor
In Visual Basic 6.0, you use the Form_Initialize and Form_Load events to
initialize your forms. In Visual Basic .NET, the Form_Initialize event has been
replaced with the class constructor Public Sub New.
Initializer
As in previous versions of Visual Basic, you can assign many property values
at design time. These design-time values are used by the run-time system to
provide initial values. In Visual Basic 6.0, properties are initialized through
the run-time system, and the code is not visible to the developer. In
Visual Basic .NET, the Windows Form Designer creates a subroutine called
InitializeComponent that contains the settings you define in the properties
window at design time. This subroutine is called from the class constructor
code.
Destructor
In previous versions of Visual Basic, you use the Form_Terminate and
Form_Unload events to provide finalization code. In Visual Basic .NET, these
events have been replaced with the class destructor Public Sub Dispose and the
Form_Closed event. When a form is shown non-modally, Dispose is called
when the form is closed. When you show forms modally, you must call the
Dispose method yourself.
12 Module 6: Using Windows Forms
DialogResult
Windows Forms allow you to easily create your own customized dialog boxes.
You can create customized dialog boxes by setting the DialogResult property
for buttons on your form and displaying the form as a dialog box. Once the
form is closed, you can use the DialogResult property of the form to determine
which button was clicked.
The following example shows how to use the DialogResult property of a
Windows Form:
Form1.ShowDialog( )
'The DialogResult property is updated when a button is pressed
and the form closed
If Form1.DialogResult = DialogResult.Yes Then
'Do something
End If
Form1.Dispose( )
Font
The Font property of a Windows Form behaves slightly differently than that of
a Visual Basic 6.0 form. Controls inherit Font.BackColor and Font.ForeColor
from their parent control. If the font is not set on a control, then the control
inherits the font from the parent. This allows you to change the font on the
form, and have all controls on the form automatically pick up that new font.
14 Module 6: Using Windows Forms
Opacity
By default, all Windows Forms are 100 percent opaque. In Windows 2000 and
Windows XP, it is possible to create forms that are transparent or translucent.
You can do this by changing the Opacity property of a form. This holds a
double value between 0 and 1, with 1 being opaque and 0 being transparent.
The following example shows how to make a form 50% opaque:
Me.Opacity = 0.5
TopMost
The TopMost property allows your form to remain on top of all other windows,
even when it does not have the focus. This is what the Windows Task Manager
does by default. In previous versions of Visual Basic, this frequently used
feature can be achieved only by using API calls. In Visual Basic .NET, you
simply assign a Boolean property of a Windows Form.
The following example shows how to toggle the TopMost property:
Me.TopMost = Not Me.TopMost
Close
This method is similar to the Unload method in Visual Basic 6.0. You can use
it to close the current form and release any resources it is holding. The
following example shows how to use the Close method of a Windows Form:
If blnEndApp = True Then
Me.Close( )
End If
16 Module 6: Using Windows Forms
Closing
This event is similar to the Visual Basic 6.0 Unload event. It occurs when the
form is being closed and allows you to cancel the closure through the use of the
CancelEventArgs argument.
The following example shows how to use the Closing event to query whether
the user wants to end the application:
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As
System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
If MessageBox.Show("Do you really want to close this form?",
"Closing", MessageBoxButtons.YesNo) = DialogResult.No Then
e.Cancel = True
End If
End Sub
Closed
The Closed event occurs after the Closing event but before the Dispose method
of a form. You can use it to perform tasks such as saving information from the
form.
The following example shows how to use the Closed event to store information
in a global variable:
Private Sub Form2_Closed(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles MyBase.Closed
strName = "Charlie"
End Sub
Handling Events
Topic Objective
To explain how to handle
events in Windows Forms.
Lead-in Handling multiple events with one procedure
Event handling has changed
significantly since Private
Private Sub
Sub AddOrEditButtonClick(ByVal
AddOrEditButtonClick(ByVal sender
sender As
As Object,
Object,
Visual Basic 6.0. ByVal
ByVal ee As
As System.EventArgs)
System.EventArgs)
Handles
Handles btnAdd.Click,
btnAdd.Click, btnEdit.Click
btnEdit.Click
Using AddHandler
AddHandler
AddHandler btnNext.Click,
btnNext.Click, AddressOf
AddressOf NavigateBtnClick
NavigateBtnClick
Using AddHandler
The AddHandler keyword allows you to add event handling to your form or
control at run time by using one of two techniques, as is described for classes in
Module 5, “Object-Oriented Programming in Visual Basic .NET,” in Course
2373B, Programming with Microsoft Visual Basic .NET. It is similar to the
Handles keyword in that it also allows you to use one event-handling procedure
for multiple events or multiple controls. With AddHandler, however, you do
not need to declare the control variable by using the WithEvents modifier. This
allows a more dynamic attaching of events to handlers.
The following example shows how to use the AddHandler keyword to assign
control events to procedure:
Private Sub NavigateBtnClick(ByVal sender As System.Object,
ByVal e As System.EventArgs)
MessageBox.Show("Moving record")
End Sub
Form1_Activated Debug.WriteLine("Activated")
Form1_Closed Debug.WriteLine("Closed")
Form1_Deactivate Debug.WriteLine("Deactivated")
Form1_SizeChanged Debug.WriteLine("Size changed")
InputBox
MsgBox
The traditional MsgBox function used by Visual Basic developers is still
provided in the .NET Framework. You use the same syntax that you used in
previous versions, except you define the display style by the MsgBoxStyle
enumeration and the resulting user decision by the MsgBoxResult enumeration.
The following example shows how to use the MsgBox function:
If MsgBox("Continue?", _
MsgBoxStyle.YesNo + MsgBoxStyle.Question, _
"Question") _
= MsgBoxResult.Yes Then
...
End If
26 Module 6: Using Windows Forms
MessageBox Class
In the .NET Framework, you use the MessageBox class for displaying a simple
message in a dialog box. It provides a Show method and integer constants for
controlling the display style of the message box. You can compare the resulting
user decision to the System.Windows.Forms.DialogResult enumeration, as
shown in the following example:
If MessageBox.Show("Continue?", "Question", _
MessageBoxButtons.YesNo, MessageBoxIcon.Question) _
= DialogResult.Yes Then
...
End If
The Show method allows extra flexibility by allowing you to optionally specify
a different form as the owner of the dialog box.
InputBox
The InputBox function is still supported in Visual Basic .NET and has not
changed from previous versions of Visual Basic.
Module 6: Using Windows Forms 27
Using Controls
Topic Objective
To provide an overview of
the topics covered in this
lesson. New Controls
Lead-in Using Control Properties
Many controls have
undergone enhancements in Using Control Methods
Visual Basic .NET, and new
controls have been added to Creating Menus
the Toolbox.
Providing User Help
Implementing Drag-and-Drop Functionality
New Controls
Topic Objective
To explain some of the
new controls in
Visual Basic .NET. CheckedListBox
Lead-in LinkLabel
There are several new
controls available in Splitter
Visual Basic .NET.
ToolTip
NotifyIcon
CheckedListBox
The CheckedListBox control allows you to use a list box with check boxes
beside each item. This is a commonly used control in Windows and was
previously available through the Style property of a standard ListBox.
The following example shows how you can use the CheckedItems property to
access the selected items in the list:
Dim intTotalChecked As Integer
For intTotalChecked = 0 To _
CheckedListBox1.CheckedItems.Count - 1
Messagebox.Show(CheckedListBox1.CheckedItems _
(intTotalChecked).ToString)
Next
30 Module 6: Using Windows Forms
LinkLabel
Using the LinkLabel control, you can display hyperlinks on a form. You can
specify the Text of the hyperlink and the VisitedLinkColor and LinkColor of
links. The default event for a LinkedLabel control is the LinkClicked event.
The following example shows how you can use this to display a Web page in a
WebBrowser control:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles MyBase.Load
LinkLabel1.Text = "www.microsoft.com"
LinkLabel1.LinkColor = Color.Blue
LinkLabel1.VisitedLinkColor = Color.Purple
End Sub
Splitter
Splitter controls have become a common feature of Microsoft applications over
the last few years. Visual Basic .NET provides a built-in control to allow the
user to resize the different sections of your form without any need for resizing
code.
To use the Splitter control, you must perform the following steps:
1. Add the control to be resized to a container.
2. Dock the control to one side of the container.
3. Add the Splitter to the container.
4. Dock the Splitter to the side of the control to be resized.
After completing these steps, when you rest the mouse pointer on the edge of
the control, the pointer will change shape and the control can be resized.
Module 6: Using Windows Forms 31
ToolTip
In Visual Basic 6.0, most built-in controls have a ToolTip property that allows
you to attach textual Help to a control. This is implemented by means of the
ToolTip control in Visual Basic .NET. You can use one ToolTip control to
implement ToolTips on many controls on your form. The following example
shows how to link the ToolTip text to be used with a particular control in the
Form_Load event:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles MyBase.Load
ToolTip1.SetToolTip(Button1, "Click to confirm")
ToolTip1.SetToolTip(Button2, "Click to cancel")
End Sub
NotifyIcon
The NotifyIcon control is a component that displays an icon in the notification
area of the Windows taskbar, like the Windows Volume Control icon. The
component is placed in the component tray of the Windows Forms Designer for
a particular form. When that form is displayed at run time, the icon will display
automatically in the notification area and will be removed when the Dispose
method of the NotifyIcon component is called. A ContextMenu can be
associated with the component so that users can right-click on the icon and
select options from the menu.
Note For more information about other new controls, search for “Controls” in
the Visual Basic .NET documentation.
32 Module 6: Using Windows Forms
Button1.Text
Button1.Text == "Click
"Click Me"
Me"
Positioning
In Visual Basic 6.0, you regularly have to write code to cope with the resizing
of a form. If a user maximizes a form at run time, the controls will stay in their
original position relative to the top left corner of a form. This means that if you
have a set of command buttons—for example, OK and Cancel—positioned
either in the top right corner of a form or across the bottom of a form, you need
to write your own code to reposition these controls. In Visual Basic .NET, this
type of functionality is built into the controls and form classes.
Anchor property
In Visual Basic .NET, you can anchor a control to the top, bottom, left, or
right side of a form (or any combination). This means that at design time
you can use the Properties window to anchor a control, and you no longer
need to write repositioning code in the Resize event of a form.
Resizing
Because you can anchor any or all of the sides of a control, you can
effectively resize a control to correspond to the resizing of a form. If you
have a form containing a picture box that you want to fill the form, you can
anchor it to all sides, and it will remain the same distance from the edges of
the form at all times. This feature cannot override the size restrictions
applied to some of the Visual Basic .NET controls, such as the height of a
combo box.
Location property
This property allows you to specify the location of a control with respect to
the top left corner of its container. The property takes a Point data type,
which represents an x and y coordinate pair. This property replaces the Top
and Left properties used in Visual Basic 6.
Module 6: Using Windows Forms 33
Text Property
In earlier versions of Visual Basic, you used different methods to set the text
displayed in the various controls. For instance, Forms and Label controls
have a Caption property, whereas TextBox controls have a Text property. In
Visual Basic .NET, any textual property of a control is determined by the Text
property. This provides consistency within Visual Basic, and with the other
.NET-compatible languages.
The following example shows how to initialize a Button control in the
Form_Load or InitializeComponent procedures.
Button1.Top = 20
Button1.Height = 50
Button1.Left = 20
Button1.Width = 120
Button1.Text = "Click Me"
34 Module 6: Using Windows Forms
Focus
TextBox1.Focus(
TextBox1.Focus( ))
TextBox1.SelectAll(
TextBox1.SelectAll( ))
Focus
You can use this method to set the focus to a specific control. It is similar to the
SetFocus method used in Visual Basic 6.0. The following example shows how
to check the Text property of a TextBox control and return focus to the control
if the text is not valid:
If TextBox1.Text <> "password" Then
MessageBox.Show("Incorrect password")
TextBox1.Focus( )
TextBox1.SelectAll( )
End If
When trapping focus events, you should use the Enter and Leave events, rather
than the GotFocus and LostFocus events.
Module 6: Using Windows Forms 35
Creating Menus
Topic Objective
To explain the new changes
to menu creation.
Menu classes
Lead-in
Menus have been greatly Creating menus at design time
enhanced in
Visual Basic .NET. Use the Menu Designer
Creating menus at run time
Dim
Dim mnuMain
mnuMain As
As New
New MainMenu(
MainMenu( ))
Dim
Dim mnuItem1
mnuItem1 As
As New
New MenuItem,
MenuItem, mnuItem2
mnuItem2 As
As New
New MenuItem(
MenuItem( ))
mnuItem1.Text = "File"
mnuItem1.Text = "File"
mnuMain.MenuItems.Add(mnuItem1)
mnuMain.MenuItems.Add(mnuItem1)
mnuItem2.Text
mnuItem2.Text == "Exit"
"Exit"
mnuMain.MenuItems(0).MenuItems.Add(mnuItem2)
mnuMain.MenuItems(0).MenuItems.Add(mnuItem2)
AddHandler
AddHandler mnuItem2.Click,
mnuItem2.Click, AddressOf
AddressOf NewExitHandler
NewExitHandler
Menu = mnuMain
Menu = mnuMain
Menu Classes
There are three main classes that you will use when creating menus:
MainMenu
You use the MainMenu class to create a standard Windows menu bar at the
top of a form.
ContextMenu
You use the ContextMenu class to define pop-up menus associated with
particular controls.
MenuItem
You use the MenuItem class to define menu items within a MainMenu or a
ContextMenu.
36 Module 6: Using Windows Forms
mnuItem1.Text = "File"
mnuMain.MenuItems.Add(mnuItem1)
mnuItem2.Text = "Exit"
mnuMain.MenuItems(0).MenuItems.Add(mnuItem2)
AddHandler mnuItem2.Click, AddressOf NewExitHandler
Menu = mnuMain
Module 6: Using Windows Forms 37
The Validating event is raised whenever the next control receives focus,
providing that the next control has CausesValidation property set to True,
allowing the Text property of the control to be tested. If this property contains
an empty string, the ErrorProvider will display an exclamation icon next to
the control and update the ToolTip for the error. If the error message is an
empty string, the icon does not appear.
38 Module 6: Using Windows Forms
HelpProvider Control
You can use the HelpProvider control to display a simple pop-up Help window
or online Help from a Help file specified by the
HelpProvider.HelpNamespace property. This Help is automatically activated
when the user presses the F1 Help key while a control has focus.
Using SetShowHelp
You can also turn Help on or off for an individual control by using the
SetShowHelp method of the HelpProvider control as shown in this example:
Sub SetTextboxHelp( )
HelpProvider1.SetHelpString(TextBox1, "This is my help")
HelpProvider1.SetShowHelp(TextBox1, True) 'True = On
End Sub
Module 6: Using Windows Forms 39
Prerequisites
Before working on this lab, you must have designed forms in previous versions
of Visual Basic.
Scenario
In this lab, you will continue working with the Cargo system. The Customer
class from Lab 5.1 of Course 2373B, Programming with Microsoft
Visual Basic .NET, has been enhanced for you, and a CustomerList class has
been provided so you can iterate through the customers. The basic Customer
form has been provided for you, but it requires further development.
Exercise 1
Extending the Customer Form
In this exercise, you will enhance the existing Customer form by using the
layout properties of the controls and form. The form is currently only intended
to retrieve customer information.
2. Set the following properties for the form and controls in the Properties
window.
Object Property Value
Exercise 2
Adding a Menu and ToolTips
In this exercise, you will add a menu and ToolTips to the frmCustomer form.
To add a menu
1. Open the frmCustomer.vb design window.
2. Using the Toolbox, add a MainMenu control, renaming it mnuMain.
3. Using the Menu Designer, add menu items as shown in the following
illustration.
&File mnuFile
&Load Customers mnuFileLoad
- mnuFileSeparator
E&xit mnuFileExit
5. Create the Click event handler for the mnuFileLoad menu item.
Module 6: Using Windows Forms 53
6. From the Sub New procedure, cut the existing code for loading customers,
and paste it into the new event handler (making sure to leave the
MinimumSize code that was added in the previous exercise as it is). Your
code should now look as follows:
Public Sub New( )
MyBase.New( )
Me.MinimumSize = Me.Size
End Sub
Exercise 3
Adding a Shortcut Menu
In this exercise, you will programmatically add a shortcut menu for the
customer ListBox control.
5. Disable this menu item until there are entries in the list box, as shown in the
following code:
mItem.Enabled = False
6. Add an event handler for the new mItem object by using the AddHandler
function, as shown in the following code:
AddHandler mItem.Click, AddressOf onDeleteClick
4. Insert an If statement into the procedure to test to see whether the number of
items in lstCustomers is zero. (Hint: Use the lstCustomers.Items.Count
property).
5. In the True section, disable the Delete menu item.
6. Save the project.
If Time Permits
Creating an About Box Form Using Visual Inheritance
In this optional exercise, you will create an About box form by inheriting from
an existing base form.
&Help mnuHelp
&About… mnuHelpAbout
3. Create the Click event handler for the mnuHelpAbout menu item, and add
the following code:
Dim aboutForm As New frmAbout( )
aboutForm.ShowDialog( )
Review
Topic Objective
To reinforce module
objectives by reviewing key
points. Why Use Windows Forms?
Lead-in Structure of Windows Forms
The review questions cover
some of the key concepts Using Windows Forms
taught in the module.
Using Controls
Windows Forms Inheritance
2. The ContainerControl class is the fundamental base class for all other
controls. True or false?
False. The Control class is the fundamental base class for all other
controls.
3. Write the code to access the path from which an executable is running.
Dim strAppPath as String
strAppPath = Application.StartupPath
5. Write code to make the code behind a button called btnOK execute when a
user presses RETURN.
Me.AcceptButton = btnOK
7. Write code to create a Help menu with one menu item—About— at run
time.
Dim mnuMain As New MainMenu( )
Dim mnuItem1 As New MenuItem( )
Dim mnuItem2 As New MenuItem( )
mnuItem1.Text = "Help"
mnuMain.MenuItems.Add(mnuItem1)
mnuItem2.Text = "About"
mnuMain.MenuItems(0).MenuItems.Add(mnuItem2)
AddHandler mnuItem2.Click, AddressOf AboutClick
Menu = mnuMain
THIS PAGE INTENTIONALLY LEFT BLANK