Course 2555 Module 1
Course 2555 Module 1
Windows Forms
Contents
Overview 1
Lesson: Creating a Form 2
Lesson: Adding Controls to a Form 17
Lesson: Creating an Inherited Form 26
Lesson: Organizing Controls on a Form 35
Lesson: Creating MDI Applications 43
Review 52
Lab 1.1: Creating Windows Forms 54
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.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 1: Introducing Windows Forms 1
Overview
! Creating a Form
! Adding Controls to a Form
! Creating an Inherited Form
! Organizing Controls on a Form
! Creating MDI Applications
Introduction Windows Forms is part of the new Microsoft® .NET Framework, and it uses
many new technologies including a common application framework, managed
execution environment, integrated security, and object-oriented design
principles. In addition, Windows Forms offers full support for quickly and
easily connecting to Extensible Markup Language (XML) Web services and
building rich, data-aware applications based on the ADO.NET data model.
With the new shared development environment in the Microsoft
Visual Studio® .NET development system, developers are able to create
Windows Forms applications by using any of the languages supporting the
.NET platform, including the Microsoft Visual C#™ .NET and Microsoft
Visual Basic® .NET development systems.
Objectives After completing this module, you will be able to:
! Create a form and add controls to it.
! Create an inherited form by using Visual Inheritance.
! Organize controls on a form.
! Create Multiple Document Interface (MDI) applications.
2 Module 1: Introducing Windows Forms
Introduction Forms are the basic element of the user interface (UI) in applications created for
the Microsoft Windows® operating system. They provide a framework that you
can use throughout your application to give it a consistent look and feel. A form
in Windows-based applications is used to present information to the user and to
accept input from the user.
Forms expose properties that define their appearance, methods that define their
behavior, and events that define their interaction with the user. By setting the
properties of the form and writing code to respond to its events, you customize
the form to meet the requirements of your application. A form is a control
derived from the Form class, which in turn derives from the Control class. The
framework also allows you to inherit from existing forms to add functionality or
modify existing behavior. When you add a form to your project, you can choose
whether it inherits from the Form class provided by the .NET Framework or
from a form you created previously.
This lesson covers the basic concepts of forms and how to add controls to
forms.
Lesson objectives After completing this lesson, you will be able to:
! Describe a form.
! Determine whether to use Windows Forms or Web Forms in a scenario.
! Create a form.
! Set the properties of a form.
! Describe the events and methods in the forms life cycle.
Module 1: Introducing Windows Forms 3
Introduction When designing applications that involve a user interface, you have two
choices: Windows Forms and Web Forms. Both have full design-time support
in the development environment and can provide a rich user interface and
advanced application functionality to solve business problems. When you have
multiple options, it is important for you to know which option to use when.
Windows Forms Windows Forms are used to develop applications where the client is expected to
shoulder a significant amount of the processing burden in an application. These
include classic desktop applications for the Microsoft Win32® application
programming interface. Examples include drawing or graphics applications,
data-entry systems, point-of-sale systems, and games. All of these applications
rely on the power of the desktop computer for processing and high-performance
content display.
Web Forms ASP.NET Web Forms are used to create applications in which the primary user
interface is a browser. This includes applications intended to be available
publicly on the World Wide Web, such as e-commerce applications.
4 Module 1: Introducing Windows Forms
Windows Forms vs. Web The following table provides a comparison of different application criteria and
Forms how Windows Forms and Web Forms technologies address these criteria.
Feature/criterion Windows Forms Web Forms
(continued)
Feature/criterion Windows Forms Web Forms
Introduction In a Windows-based application, the form is the primary element for user
interaction. By combining controls and your own actions, you can request
information from the user and respond to it.
In Visual Studio .NET, a form is a window used in your application. When you
create a new Windows Application project, Visual Studio .NET provides a
Designer view that contains a form. The default form contains the minimum
elements used by most forms: a title bar, a control box, and Minimize,
Maximize, and Close buttons.
Procedure: Creating Most applications require more than one window. You must add a form to your
forms project for every window that your application requires.
To add additional forms to your project:
1. If Solution Explorer is not open, on the View menu, click Solution
Explorer.
2. In Solution Explorer, right-click the project name, point to Add, and then
click Add Windows Form.
3. In the Add New Item dialog box, in the Name box, type an appropriate
name for the form, and then click Open.
Module 1: Introducing Windows Forms 7
Events
Events Button
Button
Form
Form Name
Name
Categorized
Categorized Button
Button
Alphabetic
Alphabetic Button
Button
Description
Description Pane
Pane
Introduction When you are building the user interface of a Windows-based application, you
must set the properties for the objects that you create.
Common form The following table describes some common form properties that you typically
properties set at design time.
Property Description Default setting
(Name) Sets the name of the form in your Form1 (Form2, Form3,
project. (This is not the name that and so on)
is displayed to the user in the
caption bar but rather the name that
you will use in your code to
reference the form.)
Important: If you change the
(Name) property of your form, you
must set the startup object for your
project to the new name or the
project will not start correctly. For
information about how to change
the startup object, see Form Life
Cycle in this lesson in this module.
AcceptButton Sets which button is clicked when None
the user presses the ENTER key.
Note: You must have at least one
button on your form to use this
property.
CancelButton Sets which button is clicked when None
the user presses the ESC key.
Note: You must have at least one
button on your form to use this
property.
8 Module 1: Introducing Windows Forms
(continued)
Property Description Default setting
Procedure: Setting form You can set form properties either by writing code or by using the Properties
properties window. Any property settings that you establish at design time are used as the
initial settings each time your application runs.
To set form properties at design time:
1. If the Properties window is not open, on the View menu, click Properties
Window.
2. In Design view, click the form for which you want to set a property. The
name of the form appears in the Object list at the top of the Properties
window.
Note When you select a property, a description of the property appears at the
bottom of the Properties window, in the Description pane.
1.
1. Form1
Form1 Show
Show 5.
5. Form2
Form2 Load
Load
7.
7. Form2
Form2 GotFocus
GotFocus
2.
2. Form1
Form1 Load
Load 4.
4. Form2
Form2 Show
Show 8.
8. Form2
Form2 Activated
Activated
3.
3. Form1
Form1 Activated
Activated
6. 9.
9. Focus
Focus shifts
shifts 10.
10. Form2
Form2 LostFocus
LostFocus
6. Form1
Form1 Deactivate
Deactivate
back
back to
to Form1
Form1 11.
11. Form2
Form2 Deactivate
Deactivate
12.
12. Form1
Form1 Activated
Activated
14.
14. Form1
Form1 Deactivate
Deactivate 13.
13. Close
Close Form2
Form2 15.
15. Form2
Form2 GotFocus
GotFocus
21.
21. Form1
Form1 Activated
Activated 16.
16. Form2
Form2 Activated
Activated
24.
24. Form1
Form1 Closing
Closing 17.
17. Form2
Form2 Closing
Closing
23.
23. Exit
Exit
25.
25. Form1
Form1 Closed
Closed Application
Application 18.
18. Form2
Form2 Closed
Closed
26. 19.
19. Form2 LostFocus
Form2 LostFocus
26. Form1
Form1 LostFocus
LostFocus
27. 20.
20. Form2
Form2 Deactivate
Deactivate
27. Form1
Form1 Deactivate
Deactivate
28. 22.
22. Form2
Form2 Disposed
Disposed
28. Form1
Form1 Disposed
Disposed
Introduction After adding the necessary forms to your project and setting the startup form,
you must determine which events and methods to use. The entire life cycle of a
form uses several methods and events.
Form events and When the Show() method is called, the form events and methods are generally
methods triggered in the following order:
1. Load
2. GotFocus
3. Activated
4. Closing
5. Closed
6. Deactivate
7. LostFocus
8. Dispose()
10 Module 1: Introducing Windows Forms
New The Initialize event is typically used to prepare an application for use.
Variables are assigned to initial values, and controls may be moved or resized
to accommodate initialization data.
In .NET, initialization code must be added to the form constructor after the call
to InitializeComponent() as shown in the following example:
public CalcUI()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// Add your initialization code here
//
}
Show The Show method includes an implied Load; this means that if the specified
form is not already loaded when the Show method is called, the application
automatically loads the form into memory and then displays it to the user. The
Show method can display forms as modal or modeless.
FrmSplash.Show();
You can use the ShowDialog() method to show a form as a dialog box.
Load The Load event is used to perform actions that must occur before the form
displays. It is also used to assign default values to the form and its controls.
The Load event occurs each time that a form is loaded into memory. A form’s
Load event can run multiple times during an application’s life. Load fires when
a form starts as the result of the Load statement, Show statement, or when a
reference is made to an unloaded form’s properties, methods, or controls.
Activated/Deactivate When the user moves among two or more forms, you can use the Activated and
Deactivate events to define the forms’ behaviors. The Activated event occurs
when the form is activated in code or by the user. To activate a form at run time
by using code, call the Activate method. You can use this event for tasks such
as updating the contents of the form based on changes made to the form’s data
when the form was not activated.
The Activated event fires when the form receives focus from another form in
the same project. This event fires only when the form is visible. For example, a
form loaded by using the Load statement isn’t visible unless you use the Show
method, or set the form’s Visible property to True. The Activated event fires
before the GotFocus event.
Use the following code to set the focus to a form.
FrmSplash.Focus();
Module 1: Introducing Windows Forms 11
Deactivate fires when the form loses focus to another form. This event fires
after the LostFocus event.
Both the Activated and Deactivate events fire only when focus is changing
within the same application. If you switch to a different application and then
return to the program, neither event fires.
Important If you need to add code that executes either when the form is being
displayed or when the form is being hidden, add the code to the Activated and
Deactivate event handlers instead of to the GotFocus and LostFocus event
handlers.
Closing The Closing event is useful when you need to know how the user is closing the
form. The Closing event occurs when the form receives a request to close. Data
validation can occur at this time. If there is a need to keep the form open (for
example, if data validation fails), the closing event can be canceled.
Closed The Closed event occurs when the form is closed and before the Dispose event.
Use the Closed event procedure to verify that the form should be closed or to
specify actions that take place when closing the form. You can also include
form-level validation code for closing the form or saving data to a file.
Dispose The .NET framework does not support the Terminate event. Termination code
must execute inside the Dispose method, before the call to base.Dispose().
protected override void Dispose( bool disposing )
{
// Termination code goes here.
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
The Dispose method is called automatically for the main form in an application;
you must call it explicitly for any other form.
Hide The Hide method removes a form from the screen without removing it from
memory. A hidden form’s controls are not accessible to the user, but they are
available to the running application. When a form is hidden, the user cannot
interact with the application until all code in the event procedure that caused the
form to be hidden has finished executing.
If the form is not already loaded into memory when the Hide method is called,
the Hide method loads the form but doesn’t display it.
frmMyForm.Hide();
12 Module 1: Introducing Windows Forms
Events
The .NET Framework uses a standard naming convention for event handlers.
The convention is to combine the name of the object that sends the event, an
underscore, and the name of the event. For example, the Click event of a form
named Form1 would be named Form1_Click.
Procedure To add an event handler:
1. Open the Properties windows for the form for which you want to add an
event handler.
2. Click the Event icon in the Properties window to view the events.
You will learn more about using events and event handlers in the .NET
Framework in Module 2, “Working with Controls” in Course 2555A,
Developing Microsoft .NET Applications for Windows (Visual C# .NET).
Module 1: Introducing Windows Forms 15
Introduction When you create a form by using Windows Forms Designer, the Designer
generates a lot of code that you would have to write if you were creating a form
on your own.
Designer-generated If you look at the default code for the form, you will find the following code
code generated by the Designer.
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5,
13);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new
System.EventHandler(this.Form1_Load);
}
#endregion
Introduction To create a user interface for an application, you must add controls to a form.
This lesson covers adding controls to a form.
Lesson objectives After completing this lesson, you will be able to:
! Add controls to a form.
! Add menus to a form.
! Customize the Controls Toolbox.
18 Module 1: Introducing Windows Forms
Introduction Controls are objects that are contained in form objects. Buttons, text boxes, and
labels are examples of controls.
Procedure: Adding There are two ways to add controls to a form. The first way allows you to add
controls to a form several controls quickly and then size and position them individually. The
second way gives you more initial control over the size and position of the
control.
To add controls to a form and then size and position them:
1. If the Toolbox is not open, on the View menu, click Toolbox.
2. In the Toolbox, double-click the control that you want to add. This places an
instance of the control at the default size in the upper left corner of the
active object. When adding multiple controls in this manner, they are placed
on top of each other.
3. After the controls are added, you can reposition and resize them:
a. To reposition the control, click the control to select it, and then drag the
control to the correct position.
b. To resize the control, click the control to select it, drag one of the eight
sizing handles until the control is properly sized.
Module 1: Introducing Windows Forms 19
Introduction Menus provide a structured way for users to access the commands and tools
contained in an application. Proper planning and design of menus and toolbars
is essential and ensures proper functionality and accessibility of your
application to users.
A menu control has many properties such as Name, Caption, and Index.
! The Name property identifies the menu control in code.
! The Index property identifies controls that share the same name.
! The Caption property is the text that appears on the menu bar at run time.
Right-click the
Toolbox
Click Customize
Toolbox
Introduction The Toolbox displays a variety of items for use in Visual Studio .NET projects.
The items available include .NET components, Component Object Model
(COM) components, Hypertext Markup Language (HTML) objects, code
fragments, and text. The Toolbox contains a variety of controls that you can use
to add art work, labels, buttons, list boxes, scroll bars, menus, and geometric
shapes to a user interface.
Each control that you add to a form becomes a programmable user interface
object in your application. These objects are visible to the user when the
application runs, and they operate like the standard objects in any Windows-
based application. However, there are some controls that are visible on the
Toolbox by default. You must customize the Toolbox to display such controls
on the Toolbox. For example, the StatusBarPanel control is not visible on the
Toolbox by default.
You can customize the Toolbox by adding and removing items from it. The
Customize Toolbox dialog box displays tabbed lists of components that are
recognized on your machine. Use the Customize Toolbox dialog box to add
controls to the Toolbox or remove controls from it.
Note The Customize Toolbox dialog box replaces the Customize dialog box
in previous versions of Microsoft Visual C++®.
22 Module 1: Introducing Windows Forms
Note You can add code fragments to the Toolbox by selecting the code
fragment or text and dragging it to the Toolbox. A new entry beginning with
text will appear in the Controls Toolbox.
Module 1: Introducing Windows Forms 23
Introduction In this practice, you will open an existing project and modify the properties on
the default form. You will also add controls to the form and implement the
Click event for two buttons.
Instructions ! Open the practice project
1. Use Windows Explorer and browse to
install_folder\Practices\Mod01\Mod01_01\Starter.
ControlBox false
Font Trebuchet MS, 10pt
FormBorderStyle Fixed3D
Size 300, 175
Text Hello World
24 Module 1: Introducing Windows Forms
(Name) OutputLabel
BorderStyle Fixed3D
Font Trebuchet MS, 10pt, Bold
ForeColor ActiveCaption
Location 14,30
Size 264, 23
Text (Delete existing text and leave it
blank)
TextAlign MiddleCenter
3. Click Button1.
4. Set the following properties for the Button1 control to the values provided
in the following table.
Property Value
(Name) HelloButton
Location 57, 87
Size 75,25
Text &Say Hello
5. Click Button2.
6. Set the following properties for the Button2 control to the values provided
in the following table.
Property Value
(Name) ExitButton
Location 161, 87
Size 75,25
Text E&xit
Module 1: Introducing Windows Forms 25
7. Double-click the Say Hello button to create the Click event handler.
8. In the Click event handler for HelloButton, add the following line of code:
OutputLabel.Text = "Hello, World!";
9. Switch back to Design view of the form.
10. Double click the Exit button to create the Click event handler.
11. In the Click event handler for ExitButton, add the following line of code:
this.Close();
12. Switch back to Design view of the form.
13. Set the AcceptButton property to HelloButton and the CancelButton
property to ExitButton.
! Access Modifiers
! How to Create an Inherited Form
! Practice: Creating an Inherited Form
Introduction Creating new Windows Forms by inheriting from base forms is an efficient way
to duplicate your best efforts without going through the process of entirely
recreating a form every time you require it. The process of inheriting a form
from an existing one is called Visual Inheritance. This lesson covers how to
inherit from an existing form by using Visual Inheritance.
Lesson objective After completing this lesson, you will be able to create an inherited form.
Module 1: Introducing Windows Forms 27
Access Modifiers
Access
Access Modifier
Modifier Description
Description
Read-only
Read-only to a child form, all
all of
of its
its
Private
Private property
property values
values in
in the
the property
property
browser
browser are
are disabled
disabled
Accessible
Accessible within
within the
the class
class and
and from
Protected
Protected any
any class
class that
that inherits
inherits from
from the
the class
class
that declared this member
that declared this member
Most
Most permissive
permissive level.
level. Public
Public controls
controls
Public
Public
have full accessibility
have full accessibility
Introduction Not only can you inherit controls and properties from a base form, you can also
inherit code. This means that a code library can be built to enhance code reuse.
The major advantage of using Inheritance is that you can override the code if it
is not applicable in a particular circumstance.
To be able to override an event in the child form, you must make it visible to
the child. This means that it must be defined as Public or Protected (protected
is the default for events), and its Modifiers keyword cannot be private.
Access modifiers The Modifiers property determines the accessibility level of a control, such as
how a control behaves and what functionality it has when its form is used as a
base form. An inherited form displays the controls in a different shade of grey
depending upon the value of this property. Some of the values of the Modifiers
property include Public, Private, and Protected.
28 Module 1: Introducing Windows Forms
The values of the control’s properties are the same as those on the parent object,
and when they are altered on the child form, that property becomes bold in the
Properties window. To reset all values to those held by the parent, right-click
the Properties window, and then click Reset.
! Private
A Private control is read-only to a child form. Because a Private control
cannot be modified, all of its property values in the Properties window are
disabled. Copying this control elsewhere on the form or project produces a
fully editable version.
! Protected
A protected member is accessible within the class and from any class that
inherits from the class that declared this member. If a change is made to a
Protected control on a child form, then those changes will remain even if a
change is made to the parent form. For the other types of controls, changes
to the parent form will override those made to the child.
! Public
Public is the most permissive level. Public controls have full accessibility.
Note The Public, Protected, and Private property values are the three
property values that are common across all the .NET Language projects. C#
supports two other values, Internal and Protected Internal.
Module 1: Introducing Windows Forms 29
public
public class
class Form2
Form2 :: Namespace1.Form1
Namespace1.Form1
Introduction Visual Inheritance offers many advantages to developers. If you already have
designed a form for a different project that is similar to the one you need in the
current project, you can inherit from the earlier form. It also means that you can
create a base form as a template to use later. It is a useful way of duplicating the
main functionality of particular forms without having to recreate them from the
beginning. Changes to the base form will be reflected in those forms that are
inherited from it; so changes to the underlying template form will change all
forms based on it.
Procedure: Inheriting There are two ways of implementing Visual Inheritance in a
from an existing form Visual Studio .NET project.
To create an inherited form programmatically:
1. Create a new project in Visual Studio .NET.
2. Add another form, or view the code of Form1, which is created by default.
3. In the class definition, add a reference to the form to inherit from. The
reference should include the namespace that contains the form, followed by
a period, and then the name of the base form itself.
public class Form2 : Namespace1.Form1
The form now takes on the characteristics of the inherited form. It contains
the controls that were on the inherited form, the code, and the properties.
30 Module 1: Introducing Windows Forms
Note Make sure that you build the solution before you inherit from an
existing form in the project.
1. On the Project menu, click Add Inherited Form. The dialog box is
identical for C# and for Visual Basic.
2. In the Categories pane, click Local Project Items, and in the Templates
pane, click Inherited Form. In the Name box, type a name, and then click
Open. This will open the Inheritance Picker dialog box.
3. Click Browse, and locate the compiled executable of the project that
contains your form. Click OK.
The new form should now be added into the project and be based on your
inherited form. It contains the controls on the base form.
Module 1: Introducing Windows Forms 31
Important After the new form has been added and has been inherited from the
base form, the project must be rebuilt to complete the inheritance relationship.
The new form can then be displayed in Design view.
32 Module 1: Introducing Windows Forms
Introduction In this practice, you will modify an existing form to allow it to be inherited by
other forms. You will create a new form and inherit it from the base form. You
will then modify the inherited form to customize it for a particular application.
Instructions ! Open the project file for this practice activity
1. Use Windows Explorer, and browse to
install_folder\Practices\Mod01\Mod01_02\Starter.
2. Double-click the WindowsCalculator.sln solution file to open the project.
Introduction Often you want to change the position and dimensions of controls at run time.
Currently, you handle the resize event (WM_SIZE for Application
Programming Interface [API] programmers), calculate the new position, width,
and height, and call some methods like Move or SetWindowPos. The
Windows Forms library offers two very helpful concepts to simplify these
proceedings: anchoring and docking. In addition, Visual Studio .NET provides
the Format menu, which allows you to arrange controls on a form.
This lesson covers the Format menu and how to anchor and dock controls on a
form. The lesson also covers setting the tab order for controls.
Lesson objectives After completing this lesson, you will be able to:
! Arrange controls on a form by using the Format menu.
! Set the tab order for the controls on a form.
! Anchor controls to a form.
! Dock controls on a form.
36 Module 1: Introducing Windows Forms
Introduction You can use the Format menu or the Layout Toolbar in the Visual Studio
Integrated Development Environment (IDE) to align, layer, and lock controls
on a form.
Format menu options The Format menu provides many options for organizing controls. When you
use the Format menu options for organizing controls, select controls so that the
last control that you select is the primary control to which the others are
aligned. The primary control has dark sizing handles whereas other controls
have light sizing handles around them.
The choices and their functions are listed in the following table.
Choice Description
When creating complex user interfaces, you may want to layer controls on a
form. To layer controls on a form:
1. Select a control.
2. On the Format menu, point to Order, and then click Bring To Front or
Send To Back.
You can lock all controls on a form. This prevents any accidental moving or
resizing of controls if you are setting other properties for controls. To lock all
controls on a form, on the Format menu, click Lock Controls.
38 Module 1: Introducing Windows Forms
Introduction The tab order is the order in which a user moves focus from one control to
another by pressing the TAB key. Each form has its own tab order. By default,
the tab order is the same as the order in which you created the controls. Tab
order numbering begins with zero.
Procedure: Setting the You can set tab order in the Properties window by using the TabIndex
tab order property. The TabIndex property of a control determines where it is positioned
in the tab order. By default, the first control drawn has a TabIndex value of 0,
the second has a TabIndex of 1, and so on.
To set the tab order by using the View menu:
1. On the View menu, click Tab Order.
2. Click the controls sequentially to establish the tab order that you want.
3. When you are finished, on the View menu, click Tab Order.
! Anchoring
" Ensures that the edges of
the control remain in the
same position with
respect to the parent
container
! To anchor a control to the
form
" Set its Anchor property
" Default value: Top, Left
" Other Styles: Bottom,
Right
Introduction If you are designing a form that the user can resize at run time, the controls on
the form should resize and reposition properly. When a control is anchored to a
form (or another container) and the form is resized, the control maintains the
distance between the control and the anchor positions (which is the initial
position). You use the Anchor property editor to anchor.
Procedure: Anchoring a To anchor a control on a form:
control on a form
1. Select the control that you want to anchor.
2. In the Properties window, click the Anchor property, and then click the
Anchor arrow.
The Anchor property editor is displayed; it contains a top bar, left bar, right
bar, and bottom bar.
3. To set an anchor, click the top, left, right, or bottom bar in the Anchor
property editor. Controls are anchored to the top and left by default. To clear
a side of the control that has been anchored, click the bar on that side.
40 Module 1: Introducing Windows Forms
! Docking
" Enables you to glue the edges of a control to
the edges of its parent control
! To dock a control
" Set the Dock property
Introduction You can dock controls to the edges of your form. For example,
Windows Explorer docks the TreeView control to the left side of the window
and the ListView control to the right side of the window. Use the Dock
property for all visible Windows Forms controls to define the docking mode.
If you use the Dock property, a control is coupled with two edges of the
container. Then, the control is horizontally or vertically resized when the
container is resized. In real life, you do not indicate the edges, you indicate a
border. If you dock a control to the left border, it is connected with the top left
and bottom left edge. The value of the Dock property is one of the DockStyle
values.
A special case is DockStyle.Fill. This value docks the control to all edges. The
control fills in the complete client area of the container.
Procedure: Docking a To dock a control on a form:
control on a form
1. Select the control that you want to dock.
2. In the Properties window, click the arrow to the right of the Dock property.
The Dock property editor is displayed; it contains a series of buttons that
represent the edges and the center of the form.
3. Click the button that represents the edge of the form where you want to
dock the control. To fill the contents of the control’s form or container
control, click the Fill (center) button. Click None to disable docking.
The control is automatically resized to fit the boundaries of the docked edge.
Module 1: Introducing Windows Forms 41
Introduction In this demonstration, you will see how to organize controls on a form.
Instructions
! Organizing controls by using the Format menu
1. Open the WorkingWithControls.sln solution in Visual Studio .NET from
install_folder\Democode\ Mod01\Mod01_01\Starter.
2. If the WorkingWithControls form is not visible, display it in Design view.
You will notice that the controls on the forms are not organized very well.
3. Organize the buttons on the form so that the Display button is positioned to
the left of the Exit button.
4. Click the Exit button, hold down CTRL, and click the Display button. Both
buttons are selected.
5. On the Format menu, click Align, and then click Tops. The Exit button
aligns with the top of the Display button.
6. While the two buttons are selected, on the Format menu, click Center in
Form, and then click Horizontally.
7. Select the Choose Output group box.
8. On the Format menu, click Center in Form, and then click Horizontally.
9. While the group box is selected, press the up arrow key twice to move the
group box up.
10. Select the Display Current Time option button, hold down CTRL, and then
click the Display Current Date option button.
11. On the Format menu, click Align, and then click Lefts.
42 Module 1: Introducing Windows Forms
12. While the two option buttons are selected, on the Format menu, click
Vertical spacing, and then click Increase. Perform this step a second time
further to increase the space between the two controls.
13. While the option buttons are selected, on the Format menu, click Center in
Form, and then click Horizontally.
14. While the option buttons are selected, on the Format menu, click Center in
Form, and then click Vertically.
Introduction When creating Windows-based applications, you can use different styles for the
user interface. Your application can have a single-document interface (SDI) or a
multiple-document interface (MDI), or you can create an explorer-style
interface. For more information about different types of application interfaces,
see the .NET Framework software development kit (SDK).
This lesson covers how to create and use MDI applications.
Lesson objectives After completing this lesson, you will be able to:
! List the differences between SDI and MDI applications.
! Create MDI applications.
! Explain how parent and child forms interact.
44 Module 1: Introducing Windows Forms
SDI MDI
Displays
Displays multiple
multiple documents
documents
Only
Only one
one document
document is
is visible
visible at
at the
the same
same time
time
You
You must
must close
close one
one Each
Each document
document is
is displayed
displayed
document
document before
before you
you open
open in
in its
its own
own window
window
another
another
Introduction Before you create a Windows-based application, you must determine the style
of user interface for the application.
SDI vs. MDI As the name suggests, single-document interface (SDI) applications can support
only one document at a time, whereas a multiple-document interface (MDI)
application can support several documents simultaneously. The following table
lists the differences between SDI and MDI applications and also provides
examples of which interface style to use for which scenario.
SDI MDI
Only one document is visible at a time. Several documents are visible at the same time.
Must close one document before opening another. Each document is displayed in its own window.
Example: Microsoft WordPad Example: Microsoft Excel
Scenario: A calendar application (because you may not Scenario: An insurance application in which the user
need more than one instance of a calendar open at a needs to work with multiple application forms.
time).
Module 1: Introducing Windows Forms 45
protected
protected void
void MenuItem2_OnClick(object
MenuItem2_OnClick(object sender,
sender, System.EventArgs
System.EventArgs e)
e)
{{
Form2
Form2 NewMdiChild
NewMdiChild == new
new Form2();
Form2();
//
// Set
Set the
the Parent
Parent Form
Form of
of the
the Child
Child window.
window.
NewMdiChild.MdiParent
NewMdiChild.MdiParent == this;
this;
//
// Display
Display the
the new
new form.
form.
NewMdiChild.Show();
NewMdiChild.Show();
}}
Introduction There are three main steps involved in creating an MDI application: creating a
parent form, creating a child form, and calling the child form from a parent
form.
Procedure: Creating MDI To create the parent form at design time:
applications
The Parent form in an MDI application is the form that contains the MDI child
windows. Child windows are used for interacting with users in an MDI
application.
1. Create a new project.
2. In the Properties window, set the IsMdiContainer property to True.
This designates the form as an MDI container for child windows.
Note When you are setting properties in the Properties window, you can
also set the WindowState property to Maximized. This allows you to easily
manipulate MDI child windows when the parent form is maximized.
MDI child forms are critical for MDI applications because users interact with
the application through child forms.
To create the child form at design time:
• In the same project that contains the parent form, create a new form.
46 Module 1: Introducing Windows Forms
Introduction In an MDI application, a parent form has several child forms, and each of the
child forms interacts with the parent form. Visual Studio .NET includes several
properties that allow parent and child forms in an MDI application to interact.
Procedure: Listing the An easy way to keep track of the different MDI child windows an application
child windows of a has open is to use a Window list. The functionality to keep track of all the open
parent form MDI child forms as well as which child form has focus is part of
Visual Studio .NET and is set with the MdiList property of a menu item.
To list the child windows of a parent form by using the Window list:
1. Add a MainMenu component to the parent form.
2. Add the following top-level menu items to the MainMenu component by
using the Menu Designer.
Menu item Text
MenuItem1 &File
MenuItem2 &Window
Procedure: Determining When you are completing certain procedures in an application, it is important to
the active child form determine the active form.
Because an MDI application can have many instances of the same child form,
the procedure must know which form to use. To specify the correct form, use
the ActiveMdiChild property, which returns the child form that has the focus
or that was most recently active.
Use the following code to determine the active child form.
Form activeChild = this.ActiveMdiChild;
48 Module 1: Introducing Windows Forms
Procedure: Arranging To arrange child windows on a parent form, you can use the LayoutMdi
child windows on the method with the MdiLayout enumeration to rearrange the child forms in an
parent form MDI parent form.
There are four different MdiLayout enumeration values that can be used by the
LayoutMdi method. These values help you display the form as cascading,
horizontally or vertically tiled, or as child form icons arranged along the lower
portion of the MDI form.
To arrange child forms, in an event, use the LayoutMdi method to set the
MdiLayout enumeration for the MDI parent form.
You can use the following members of the MdiLayout enumeration when
calling the LayoutMdi method of the Form class.
Member Description
11. Click the entry below the Format menu, and set the text to &Toggle
Foreground.
12. Set the Name property of the Toggle Foreground menu item to
ToggleMenuItem.
13. Double-click the Toggle Foreground menu, and add the following code to
the Click event handler:
if (ToggleMenuItem.Checked)
{
ToggleMenuItem.Checked = false;
ChildTextBox.ForeColor = System.Drawing.Color.Black;
}
else
{
ToggleMenuItem.Checked = true;
ChildTextBox.ForeColor = System.Drawing.Color.Blue;
}
Review
! Creating a Form
! Adding Controls to a Form
! Creating an Inherited Form
! Organizing Controls on a Form
! Creating MDI Applications
1. List some reasons why you would use Windows Forms as opposed to Web
Forms.
Richer user interface
Faster response time
Better support for offline scenario
5. When creating a form, what class must the form inherit from to make it a
Windows Form?
System.Windows.Forms.Form
7. When creating a form that inherits from a base form, what must be available
to override the base version of the methods of a control on the base form?
The Modifier property of the control on the base form must be set to
either protected or public to override its functionality in the derived
form.
54 Module 1: Introducing Windows Forms
Objectives After completing this lab, you will have demonstrated your ability to:
! Create a new form.
! Inherit a new form from an existing form.
! Add controls to a form.
! Set form and control properties.
Prerequisites Before working on this lab, you must have the knowledge and skills to develop
a simple Windows Forms application by using a Visual Studio .NET–
compatible programming language.
Scenario The Internal Business Application shell provides a common access point to
various internal business applications. To ensure that the information provided
by the application is viewed by the appropriate user, the application requires a
logon form.
The logon form will prompt the user for his or her user name and password.
The logon form will then attempt to authenticate the user’s credentials to
determine if the user is permitted to access various internal applications.
In this lab, you will add a new form to the Internal Business Application shell
and populate it with controls. You will also implement the Click event handler
for the buttons on the logon form. In addition, you will create the About dialog
box by inheriting a new form from an existing form.
Estimated time to
complete this lab:
30 minutes
Module 1: Introducing Windows Forms 55
Exercise 1
Creating a New Windows Form
In this exercise, you will update the Internal Business Application shell by adding a logon form and
populating it with controls. You will also set form and control properties and implement the Click
event handlers for the buttons on the logon form.
There are starter and solution files associated with this exercise. Browse to
install_folder\Labfiles\Lab01_1\Ex01\Starter to find the starter files, and browse to
install_folder\Labfiles\Lab01_1\Ex01\Solution to find the solution files. If you performed a default
installation of the course files, install_folder corresponds to C:\Program Files\Msdntrain\2555.
1. Open the InternalBusinessApp project in Visual a. For more information about opening a project file
Studio .NET. Browse to and starting an application, see the following
install_folder\Labfiles\Lab01_1\Ex01\Starter to resource:
find this project. • The Visual Studio .NET Help documentation.
Note: The project will not build until you complete For additional information about opening a
this exercise. project file, in Search, select the Search in
titles only check box, then search by using
the phrase Open Project Dialog Box. For
additional information about starting an
application from within Designer, in Index,
search by using the phrase Debugging
Windows Applications.
2. Add a new form to the project. Use the form a. For more information about Windows Forms, see
name LoginForm, and use the file name the following resources:
LoginForm.cs. • Practice: Creating a Form in Module 1,
“Introducing Windows Forms,” in Course
2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
This practice contains information about how
to add a new form to a project.
• Lesson: Creating a Form in Module 1,
“Introducing Windows Forms,” in Course
2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
This lesson contains information about how to
create a form.
• The Windows Forms section of the .NET
Framework SDK documentation.
56 Module 1: Introducing Windows Forms
3. Set form properties. Use the following table to set a. For more information about form properties and
the properties of the form. Windows Forms, see the following resources:
Property Value • Practice: Creating a Form in Module 1,
(Name) LoginForm “Introducing Windows Forms,” in Course
ControlBox False 2555A, Developing Microsoft .NET
FormBorderStyle Fixed3D Applications for Windows (Visual C# .NET).
MaximizeBox False This practice contains information about how
MinimizeBox False to set form properties.
Size 322, 210 • Lesson: Creating a Form in Module 1,
Text Internal Business “Introducing Windows Forms,” in Course
Application Logon 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
• The Windows Forms section of the .NET
Framework SDK documentation.
4. Add controls to the form. Add two labels, two a. For more information about adding controls to a
text boxes, and two buttons to the form. form and Windows Forms, see the following
resources:
• Practice: Creating a Form, in Module 1,
“Introducing Windows Forms,” in Course
2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
• Lesson: Creating a Form, in Module 1,
“Introducing Windows Forms,” in Course
2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
• The Windows Forms section of the .NET
Framework SDK.
Module 1: Introducing Windows Forms 57
5. Set the control properties. Use the following a. For more information about control properties
tables to set the properties of the controls. and Windows Forms, see the following resources:
Label1 Property Value • Practice: Creating a Form, in Module 1,
(Name) UserNameLabel “Introducing Windows Forms,” in Course
Location 64, 31 2555A, Developing Microsoft .NET
Size 63, 14 Applications for Windows (Visual C# .NET).
Text User name: This practice contains information about how
to set control properties.
6. Set the tab order for the controls on the form. The a. For more information about setting tab order on a
tab order should resemble the following diagram. form and Windows Forms, see the following
resources:
• Lesson: Organizing Controls on a Form, in
Module 1, “Introducing Windows Forms,” in
Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
• The Windows Forms section in the .NET
Framework SDK.
7. Complete the form properties. Use the following a. For more information about setting form
table to set the remaining properties of the form. properties and Windows Forms, see the following
Property Value resources:
11. Implement the Click event handler for the Log Additional information is not necessary for this task.
On button. Open the LoginFormCode.txt file, and
copy the required code under the heading Create
a Click event handler for the Log On button and
add the following code to the event handler.
12. Build and run the application. Specify mario for a. For more information about working with forms
the user name and P@ssw0rd for the password. and Windows Forms, see the following resources:
• Practice: Creating a Form, in Module 1,
“Introducing Windows Forms,” in Course
2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
• Lesson: Creating a Form, in Module 1,
“Introducing Windows Forms,” in Course
2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
• The Windows Forms section of the .NET
Framework SDK.
60 Module 1: Introducing Windows Forms
Exercise 2
Inheriting a New Form from an Existing Windows Form
In this exercise, you will update the Internal Business Application shell by adding an About dialog
by inheriting from a generic Windows Form.
There are starter and solution files associated with this exercise. Browse to
install_folder\Labfiles\Lab01_1\Ex02\Starter to find the starter files, and browse to
install_folder\Labfiles\Lab01_1\Ex02\Solution to find the solution files. If you performed a default
installation of the course files, install_folder corresponds to C:\Program Files\Msdntrain\2555.
1. Open the InternalBusinessApp project in Visual a. For more information about opening a project file
Studio .NET. Browse to install_folder\Labfiles\ and starting an application, see the following
Lab01_1\Ex02\Starter to find this project. resource:
• The Visual Studio .NET Help documentation.
For additional information about opening a
project file, in Search, select the Search in
titles only check box, then search by using
the phrase Open Project Dialog Box. For
additional information about starting an
application from within Designer, in Index,
search by using the phrase Debugging
Windows Applications.
2. Open the BaseAboutForm form in Design view. a. For more information about adding new forms to
a project and Windows Forms, see the following
resources:
• Practice: Creating an Inherited Form, in
Module 1, “Introducing Windows Forms,” in
Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
• Lesson: Creating an Inherited Form, in
Module 1, “Introducing Windows Forms,” in
Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
• The Windows Forms section of the .NET
Framework SDK.
Module 1: Introducing Windows Forms 61
3. Use the following table to set the Modifier a. For more information about adding new forms to
property of each control. To set a property for a project and Windows Forms, see the following
multiple controls simultaneously, use the CTRL resources:
key to select the controls. • Practice: Creating an Inherited Form, in
Control Modifier Property Value Module 1, “Introducing Windows Forms,” in
ProductNameLabel protected Course 2555A, Developing Microsoft .NET
VersionNumber protected Applications for Windows (Visual C# .NET).
CopyrightLabel protected • Lesson: Creating an Inherited Form, in
AllRightsReservedLabel protected Module 1, “Introducing Windows Forms,” in
AboutOkButton protected Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
• The Windows Forms section of the .NET
Framework SDK.
4. Save the BaseAboutForm, and build the project. Additional information is not necessary for this task.
5. Add a new form to the project by using the a. For more information about adding new forms to
Inheritance Picker dialog box. Use the form a project and Windows Forms, see the following
name AppControlAboutForm. Inherit the form resources:
from the BaseAboutForm form. Save the new • Practice: Creating an Inherited Form, in
form, and build the project. Module 1, “Introducing Windows Forms,” in
Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
• Lesson: Creating an Inherited Form, in
Module 1, “Introducing Windows Forms,” in
Course 2555A, Developing Microsoft .NET
Applications for Windows (Visual C# .NET).
• The Windows Forms section of the .NET
Framework SDK.
6. Complete the properties on the a. For more information about working with
AppControlAboutForm form. Use the following inherited forms and Windows Forms, see the
table to set the properties of the form. following resources:
Form Value • Practice: Creating an Inherited Form, in
BackColor Control Module 1, “Introducing Windows Forms,” in
Size 500, 212 Course 2555A, Developing Microsoft .NET
Text About Internal Business Applications for Windows (Visual C# .NET).
Application This practice contains information about how
to set inherited form and control properties.
Use the following table to set the properties of the • Lesson: Creating and Inherited Form, in
controls. Module 1, “Introducing Windows Forms,” in
Course 2555A, Developing Microsoft .NET
Control Property Value Applications for Windows (Visual C# .NET).
ProductNameLabel.Text Internal Business This lesson contains information about how to
Application work with inherited forms.
VersionNumber.Text Version 1.0.3153 • The Windows Forms section of the .NET
CopyrightLabel.Text Copyright © 2002 Framework SDK.
Contoso, Ltd.
62 Module 1: Introducing Windows Forms
7. In AppControlForm, implement click event a. For more detailed information about the tasks that
handler for the About menu item. you must perform, see the TODO comments in
the code.
b. For more information about Windows Forms, see
the following resource:
• The Windows Forms section of the .NET
Framework SDK.
8. Run the application to test the inherited About a. For more information about Windows Forms, see
dialog box. the following resources:
• The Windows Forms section of the .NET
Framework SDK.