0% found this document useful (0 votes)
1 views64 pages

Course 2555 Module 1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views64 pages

Course 2555 Module 1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Module 1: Introducing

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.

 2002 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, Active X, Authenticode, FrontPage, IntelliSense,


MSDN, PowerPoint, Visual Basic, Visual C#, Visual Studio, Win32, and Windows Media are
either registered trademarks or trademarks of Microsoft Corporation in the United States and/or
other countries.

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

Lesson: Creating a Form

! Windows Forms vs. Web Forms


! How to Create a Form
! How to Set Form Properties
! Form Life Cycle
! How to Handle Form Events
! Windows Form Designer-Generated Code

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

Windows Forms vs. Web Forms


Feature
Feature Windows
Windows Forms
Forms Web
Web Forms
Can
Can bebe run
run without
without
Deployment
Deployment No
No download
download required
altering the
the registry
Interactive
Interactive oror dynamic
dynamic
graphics
graphics require
require round
round
Graphics
Graphics Includes
Includes GDI+ trips
trips to
to the
the server
server for
for
updates
Provide
Provide the
the quickest
quickest Can
Can take
take advantage
advantage of
Responsiveness response
Responsiveness response speed
speed for
for the browser's
browser's dynamic
dynamic
interactive applications
applications HTML to to create
create rich
rich UI
UI
Requires
Requires .NET
.NET
Platform
Platform Framework
Framework running
running on
on Require
Require only
only aa browser
browser
the
the client
client computer
computer
Programming Based
Based onon aa client-side,
client-side,
Programming Applications components
components
Win32-based
Win32-based message-
message-
model are invoked
invoked via
via HTTP
pump
pump mode
mode
Code-based and
and role-
role-
Security Role-based security
security
based security
security

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

Deployment Applications can be Have no client


downloaded, installed, and deployment; the client
run directly on the users’ requires only a browser.
computers without any The server must be running
alteration of the registry. Microsoft .NET
Framework. Updates to the
application are made by
updating code on the
server.
Graphics Windows Forms include Interactive or dynamic
GDI+, which allows graphics require round
sophisticated graphics to trips to the server for
be used for games and updates when used on Web
other extremely rich Forms. GDI+ can be used
graphical environments. on the server to create
custom graphics.
Responsiveness Windows Forms can run If you know that users will
entirely on the client have Microsoft
computer; they can provide Internet Explorer 5 or later,
the quickest response a Web Forms application
speed for applications can take advantage of the
requiring a high degree of browser’s dynamic HTML
interactivity. (DHTML) capabilities to
create a rich, responsive
UI. If users have other
browsers, most processing
(including UI-related tasks
such as validation) requires
a round trip to the Web
server, which can affect
responsiveness.
Platform Windows Forms require Web Forms require only a
the .NET Framework to be browser. DHTML-capable
running on the client browsers can take
computer. advantage of extra
features, but Web Forms
can be designed to work
with all browsers. The
Web server must be
running .NET Framework.
Module 1: Introducing Windows Forms 5

(continued)
Feature/criterion Windows Forms Web Forms

Programming model Windows Forms are based Web Forms rely on a


on a client-side, Win32- largely asynchronous,
based message-pump disconnected model, in
mode, in which instances which components are
of components are created, loosely coupled to the
used, and discarded by the application front end.
developer. Typically, application
components are invoked
by HTTP. This model may
not be suitable for
applications that require
extreme throughput from
the user end or for those
with high-volume
transactions. Similarly,
Web Forms applications
may not be suitable for
database applications that
require high levels of
concurrency control (for
example, pessimistic
locking).
Security Windows Forms use Web Forms allow you to
granular permissions in its control the identity under
implementation of code which server application
access security to protect code is executed.
computer resources and Applications can execute
sensitive information. This code by using the identity
allows careful exposure of of the requesting entity,
functionality, while which is known as
retaining security. impersonation.
Applications can also
dynamically tailor content
based on the requestor’s
identity or role. For
example, a manager could
receive access to a site or
to content that requires a
higher level of security
than someone with lesser
credentials.
6 Module 1: Introducing Windows Forms

How to Create a Form

! A base form is created


when you create a new
project
! To create a new form
1. Right-click the project
in Solution Explorer
2. Click Add
3. Click Add Windows
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

How to Set Form Properties

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

ControlBox Determines whether a form True


displays a control box in the
caption bar. The control box can
contain the Minimize button,
Maximize button, Help button,
and the Close button.
FormBorderStyle Controls the appearance of the Sizable
border for the form. This will also
affect how the caption bar appears
and what buttons appear on it.
MaximizeBox Determines whether a form has a True
Maximize button in the upper right
corner of its caption bar.
MinimizeBox Determines whether a form has a True
Minimize button in the upper right
corner of its caption bar.
StartPosition Determines the position of a form WindowsDefaultLocation
on the screen when it first appears.
Text Sets the text displayed in the Form1 (Form2, Form3,
caption bar of the control. and so on)

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.

3. Use the Alphabetic and Categorized buttons in the Properties


window to choose whether to view the form properties alphabetically or by
category.
4. In the Properties window, click the property that you want to set.

Note When you select a property, a description of the property appears at the
bottom of the Properties window, in the Description pane.

5. Type or select the property setting that you want.


Module 1: Introducing Windows Forms 9

Form Life Cycle

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

How to Handle Form Events

Events

Introduction An event handler is a segment of code that is called when a corresponding


event occurs. For example, you can write code in an event handler for the
Activated event of a form to perform operations such as updating the data
displayed in the controls of the form when the form is activated.
Module 1: Introducing Windows Forms 13

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.

3. Double-click the event to add an event handler.


14 Module 1: Introducing Windows Forms

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

Windows Forms Designer-Generated Code

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

Notice the InitializeComponent section. This code is used by the development


environment to persist the property values you set in the Windows Forms
Designer.
16 Module 1: Introducing Windows Forms

Important Avoid modifying or deleting the Windows Forms Designer-


generated code. Modifying or deleting this code can result in errors in your
project.
Module 1: Introducing Windows Forms 17

Lesson: Adding Controls to a Form

! How to Add Controls to a Form


! How to Add Menus to a Form
! How to Customize the Controls Toolbox
! Practice: Creating a Form and Adding Controls

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

How to Add Controls to a Form

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

To size and position controls while you add them to a form:


1. If the Toolbox is not open, on the View menu, click Toolbox.
2. In the Toolbox, click the control that you want to add.
3. Move the mouse pointer over the form. The pointer symbol changes to a
crosshair.
4. Position the crosshair where you want the upper left corner of the control.
5. Click and drag the crosshair where you want the lower right corner. A
rectangle that indicates the control’s size and location is drawn on the
screen.
6. When the control is correctly sized, release the mouse button. The sized
control appears in the correct location on the form.
7. You can reposition or resize the control after you have released the mouse
button:
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, and drag one of the
eight sizing handles until the control is properly sized.
20 Module 1: Introducing Windows Forms

How to Add Menus to a Form

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.

Procedure: Adding To add menus to a form:


menus to a form
1. If the Toolbox is not open, on the View menu, click Toolbox.
2. In the Toolbox, double-click the MainMenu control.
3. In the Caption box, on the newly created menu, type the text for the first
menu’s title. This title will appear on the menu bar.
4. In the Name box, in the Properties window, type the name that you will use
to refer to the menu control in code.
Module 1: Introducing Windows Forms 21

How to Customize the Controls Toolbox

Right-click the
Toolbox

Click Customize
Toolbox

Select the required


control on the .NET
Framework
Components page

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

Procedure: Customizing To customize the Controls Toolbox:


the Controls Toolbox
1. Right-click the Toolbox.
2. Click Customize Toolbox.
3. Click the .NET Framework Components tab or the COM Components
tab, and select the required controls.

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

Practice: Creating a Form and Adding Controls

In this practice, you will


" Set the properties of the form
" Add controls to the form
" Set the properties of the controls
" Implement the button Click event handler

Begin reviewing the objectives for 10 min


this practice activity

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.

Note If you performed a default installation of the course files,


install_folder corresponds to C:\Program Files\Msdntrain\2555.

2. Double-click the CreatingForms.sln solution file to open the project.

! Set the properties of a form


1. Open the CreatingForms.cs file in Design view.
2. If the Properties window is not visible, on the View menu, click Properties
Window.
3. Set the remaining form properties to the indicated values.
Property Value

ControlBox false
Font Trebuchet MS, 10pt
FormBorderStyle Fixed3D
Size 300, 175
Text Hello World
24 Module 1: Introducing Windows Forms

! Add controls to the form


1. If the Toolbox is not visible, on the View menu, click Toolbox.
2. In the Toolbox, double-click the Label control to add it to the form.
3. Double-click the Button control to add it to the form.
4. Double-click the Button control again to add a second button to the form.
5. Position the Label control near the top center of the form.
6. Position the buttons next to each other near the bottom of the form—with
button1 on the left and button2 on the right.

! Set the properties of the controls


1. Click the Label1 control.
2. Set the following properties for the Label1 control to the values provided.
Property Value

(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.

! Build and run the application


1. To build the application, click the Build menu, and then click Build
Solution.
2. Run the application by pressing F5.
26 Module 1: Introducing Windows Forms

Lesson: Creating an Inherited Form

! 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

How to Create an Inherited Form

Create an inherited form by using


the Inheritance Picker dialog box

Create an inherited form


programmatically

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

To create an inherited form by using the Inheritance Picker dialog box:

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

Practice: Creating an Inherited Form

In this practice, you will


" Set the properties of the controls on the
base form to prepare them for inheritance
" Add a new form to the project inheriting it
from the base form
" Set the properties on the inherited form
and the controls

Begin reviewing the objectives for 10 min


this practice activity

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.

! Modify a form’s properties


1. If Solution Explorer is not visible, on the View menu, click Solution
Explorer.
2. If the Properties window is not visible, on the View menu, click Properties
Window.
3. Open BaseAboutForm.cs in Design view.
4. Click the Product Name label, and ensure that the Modifiers property is set
to Protected.
5. Ensure that the Modifiers property is set to the given values for the
following controls.
Control Modifiers Property

Version <1.0.0000> Label Protected


Copyright © yyyy Contoso, Ltd. Label Protected
All Rights Reserved Label Protected
OK button Protected

6. Save the project.


Module 1: Introducing Windows Forms 33

! Add an inherited form


1. From the Project menu, click Add New Item.
2. In the Categories pane, click Local Project Items.
3. In the Templates pane, click Inherited Form.
4. In the Name field, type AboutForm.cs and then click Open to open the
form.
5. In the Inheritance Picker dialog box, select BaseAboutForm.
6. Build the project.
This creates the inheritance relationship between the two forms, including
the access modifiers for the forms and controls.
7. Open AboutForm.cs and switch to Design view.
8. Set the form’s Size property to 504,216.
9. Set the BackColor property of the form to Control.
10. Set the Text property to About Simple Windows Calculator.
11. Click the Product Name label. Set the Text property to Simple Windows
Calculator.
12. Set the properties for the following controls.
Control Properties

Version <1.0.0000> Label Text: Version 2.53.1892


Copyright © yyyy Contoso, Ltd. Label Text: Copyright © 2002 Contoso, Ltd.
34 Module 1: Introducing Windows Forms

! Implement the About menu item and test the application


1. Open the source code for CalcUI.cs.
2. On the View menu, click Show Tasks, and then click Comment.
3. In the Task List window, locate the TODO comment. Add code to show the
About window when the menu item is clicked:
AboutForm aboutForm = new AboutForm();
aboutForm.ShowDialog();
4. Build and run the application.
5. When the Simple Calculator window appears, on the Help menu, click
About. The inherited About box will appear. Notice that the background of
the System Info button is still the background set on the base form, but the
other controls have the background color set in the inherited form.
Module 1: Introducing Windows Forms 35

Lesson: Organizing Controls on a Form

! How to Arrange Controls on a Form by Using the


Format Menu
! How to Set the Tab Order for Controls
! How to Anchor a Control in Windows Forms
! How to Dock a Control in Windows Forms
! Demonstration: Organizing Controls on a Form

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

How to Arrange Controls on a Form by Using the Format Menu

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

Align Aligns all the controls with respect to the


primary control
Make Same Size Resizes multiple controls on a form
Horizontal Spacing Increases horizontal spacing between
controls
Vertical Spacing Increases vertical spacing between
controls
Center in Form Centers the controls on a form
Order Layers controls on a form
Lock Controls Locks all controls on a form
Module 1: Introducing Windows Forms 37

Procedure: Arranging To align multiple controls:


controls on a form
1. In the Windows Forms Designer, open the form that contains the controls
that you want to position.
2. Select the controls that you want to align so that the last control that you
select is the primary control to which the others are aligned.
• On the Format menu, point to Align, and then click any of the seven
choices available.

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

How to Set the Tab Order for Controls

! To set the tab order for


controls
" On the View menu,
select Tab Order
" Click a control to
change its tab order
-- OR --
" Set the TabIndex property
" Set the TabStop property
to True

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.

To set the tab order by using the TabIndex property:


1. Select the control.
2. Set the TabIndex property to the required value.
3. Set the TabStop property to True.
By turning off the TabStop property, you enable a control be passed over in
the tab order of the form. A control in which the TabStop property has been
set to False still maintains its position in the tab order, even though the
control is skipped when you cycle through the controls with the TAB key.
Module 1: Introducing Windows Forms 39

How to Anchor a Control in Windows Forms

! 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

How to Dock a Control in 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

Demonstration: Organizing Controls on a Form

In this demonstration, you will see how to


" Align controls on a form
" Layer controls on a form
" Anchor controls to a form
" Dock controls on a form

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.

! Set the tab order


1. On the View menu, click Tab Order.
2. Change the tab order by clicking each of the controls. Click the controls in
the following order: Label, Display button, Exit button, Choose Output
group box, Display Current Date option button, and Display Current
Time option button. The resulting tab order will look like this.

3. On the View menu, click Tab Order.

! Anchor and dock the controls


1. Click the Label control, and then set the Dock property to Top.
2. Click the Exit button, and then set the Anchor property to Top, Right.
3. Click the Groupbox control, and then set the Anchor property to Bottom,
Left, Right.
4. Click the Display Current Date option button, and then set the Anchor
property to Top.
5. Click the Display Current Time button, and then set the Anchor property
to Bottom.
6. Build and run the application.
7. When the form appears, resize it to see how the controls behave with regard
to their positioning.
Module 1: Introducing Windows Forms 43

Lesson: Creating MDI Applications

! SDI vs. MDI Applications


! How to Create MDI Applications
! How Parent and Child Forms Interact
! Practice: Creating an MDI Application

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 vs. MDI Applications

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

How to Create MDI Applications

! To create a parent form


" Create a new project
" Set the IsMdiContainer property to True
" Add a menu item to invoke the child form
! To create a child form
" Add a new form to the project
! To call a child form from a parent form

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.

3. From the Toolbox, drag a MainMenu component to the form.


You need a menu to invoke the child forms from the parent form. As an
example, create a top-level menu item with the Text property set to &File
with submenu items called &New and &Close. Also, create a top-level
menu item called &Window.
4. Set the MdiList property of the Windows menu item to True.

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

To call the child form from the parent form:


1. Create a Click event handler for the New menu item on the parent form.
2. Insert code similar to the following code to create a new MDI child form
when the user clicks the New menu item.
protected void MenuItem2_OnClick(object sender,
System.EventArgs e)
{
Form2 NewMdiChild = new Form2();
// Set the Parent Form of the Child window.
NewMdiChild.MdiParent = this;
// Display the new form.
NewMdiChild.Show();
}
Module 1: Introducing Windows Forms 47

How Parent and Child Forms Interact

! To list the available child windows that are owned by


the parent
" Create a menu item (Windows) and set its MdiList
property to True
! To determine the active MDI child
" Use the ActiveMdiChild property
Form
Form activeChild
activeChild == this.ActiveMdiChild;
this.ActiveMdiChild;

! To arrange child windows on the parent form


" Call the LayoutMdi method

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

3. Set the MdiList property of the Windows menu item to True.

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

ArrangeIcons All MDI child icons are arranged in the


client region of the MDI parent form.

Cascade All MDI child windows are cascaded in


the client region of the MDI parent form.
TileHorizontal All MDI child windows are tiled
horizontally in the client region of the
MDI parent form.
TileVertical All MDI child windows are tiled vertically
in the client region of the MDI parent
form.

The following example uses the Cascade setting of the MdiLayout


enumeration for the child windows of the MDI parent form (Form1).
protected void CascadeWindows_Click(object sender,
System.EventArgs e)
{
Form1.LayoutMdi(System.Windows.Forms.MdiLayout.Cascade);
}
Module 1: Introducing Windows Forms 49

Practice: Creating an MDI Application

In this practice, you will


" Create the parent form
" Create the child form
" Display the child form from the parent form

Begin reviewing the objectives for 15 min


this practice activity

Introduction In this practice, you will create an MDI application.


Instructions
! Open the practice project
1. Use Windows Explorer, and browse to
install_folder\Practices\Mod01\Mod01_03\Starter.
2. Double-click the MdiApplication.sln solution file to open the project.

! Create the parent form


1. Open ParentForm.cs in Design view.
2. Set the IsMdiContainer property to True.

! Create the File menu


1. Open the Toolbox, add the MainMenu control to the form, and set its
Name property to MdiMenu.
2. Click the menu at the top of the form and set the name of the first menu item
to &File.
3. Set the Name property of the File menu to FileMenuItem and the
MergeOrder property to 0.
4. Open the File menu.
5. Click the menu item that appears under File, and set its Text property to
&New.
6. Set the Name property of the New menu to NewMenuItem.
7. Click the menu item that appears under New, and set its Text property to
&Exit.
50 Module 1: Introducing Windows Forms

8. Set the Name property of the Exit menu to ExitMenuItem.


9. Double-click the Exit menu item to create the Click event handler.
10. In the exit event handler, add the following code:
this.Close();

! Create the Window menu


1. Switch to Design view.
2. Click the second menu item to the right of File, and set its Text property to
&Window.
3. Set the Name property of the Window menu to WindowMenuItem and the
MergeOrder property to 2.
4. Set the MdiList property of the Window menu item to True.
5. Open the Window menu.
6. Click the menu item that appears under Window, and set its Text property
to &Cascade.
7. Set the Name property of the Cascade menu to
WindowCascadeMenuItem.
8. Click the menu item that appears under Cascade, and set its Text property
name to &Tile.
9. Set the Name property of the Tile menu to WindowTileMenuItem.
10. Double-click the Cascade menu, and add the following code to the Click
event handler:
this.LayoutMdi (System.Windows.Forms.MdiLayout.Cascade);
11. Return to Design view and double-click the Tile menu item.
12. Add the following code to the Click event handler for the Tile menu item:
this.LayoutMdi
(System.Windows.Forms.MdiLayout.TileHorizontal);

! Create the child form


1. Open the Project menu, and click Add Windows Form.
2. Set the name of the form to ChildForm.cs.
3. Set the Text property of the form to Child Form.
4. From the Toolbox, drag a RichTextBox control to the form, and set its
Name property to ChildTextBox.
5. Set the Dock property of the RichTextBox to Fill.
6. Delete the existing value of the Text property of the RichTextBox and
leave it blank.
7. From the Toolbox, drag a MainMenu control to the form.
8. Set the Name property of the MainMenu control to ChildWindowMenu.
9. Click the menu at the top of the form, and set the text to F&ormat.
10. Set the Name property of the Format menu to FormatMenuItem, and set
the MergeOrder property to 1.
Module 1: Introducing Windows Forms 51

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;
}

! Display the child form from the parent form


1. View ParentForm in Design view.
2. Double-click the New menu item on the File menu to create the Click event
handler.
3. Add the following code to the Click event for the New menu item:
ChildForm newChild = new ChildForm();
newChild.MdiParent = this;
newChild.Show();

! Build and run the application


1. Build the application and run it.
2. When the parent form appears, on the File menu, click New.
A new child window appears inside the parent window. Notice how the
menu from the child window merges with the menu of the parent window
and orders the menu according to the MergeOrder properties set in the
Display the child form from the parent form procedure.
3. Type some text in the child form and use the Format menu to change the
color of the text.
4. Open a few more child windows.
5. Click the Window menu, and select Tile. Notice how the child windows are
reorganized in a tiled manner.
6. Close all the child windows.
Notice that when the last child window is closed, the menu in the parent
form changes and does not display the Format menu.
7. On the File menu, click Exit to end the application.
52 Module 1: Introducing Windows Forms

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

2. What is Visual Inheritance?


The process of inheriting a form from an existing one is called Visual
Inheritance.
It means that if you already have designed a form for a different project
that is similar to the one you need now, you can inherit from it. It also
means that you can create a base form as a template for later use. It is a
useful way of duplicating the main functionality of particular forms
without having to recreate them from the beginning.

3. What is the difference between anchoring and docking a control to a form?


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).
In docking, a control is coupled with two edges of the container. The
control is horizontally or vertically resized when the container is
resized.
Module 1: Introducing Windows Forms 53

4. What are the differences between SDI and MDI applications?


In an SDI application, only one document can be open at a time. You
must close one document before opening another.
In an MDI application, several documents can be open at the same
time. Each document is displayed in its own window.

5. When creating a form, what class must the form inherit from to make it a
Windows Form?
System.Windows.Forms.Form

6. You want to perform some totaling of numbers as a form is being dismissed.


Into which event handler should you add the code?
The code should be added to the Deactivated event handler.

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

Lab 1.1: Creating Windows Forms

! Exercise 1: Creating a New Windows Form


! Exercise 2: Inheriting a New Form from an
Existing Windows Form

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.

Note This lab focuses on the concepts in Module 1, “Introducing Windows


Forms,” in Course 2555A, Developing Microsoft .NET Applications for
Windows (Visual C# .NET). As a result, this lab may not comply with Microsoft
security recommendations.

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.

Tasks Additional information

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

Tasks Additional information

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

Tasks Additional information

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.

Label2 Property Value • Lesson: Creating a Form, in Module 1,


“Introducing Windows Forms,” in Course
(Name) PasswordLabel 2555A, Developing Microsoft .NET
Location 64, 71 Applications for Windows (Visual C# .NET).
Size 64, 14
Text Password: • The Windows Forms section of the .NET
Framework SDK.

Textbox1 Property Value


(Name) UserNameTextBox
Location 128, 29
Size 120, 20
Text (Delete existing text and
leave it blank)

Textbox2 Property Value


(Name) PasswordTextBox
Location 128, 64
PasswordChar *
Size 120, 20
Text

Button1 Property Value


(Name) LogonButton
Location 67, 116
Size 75, 30
Text &Log On

Button2 Property Value


(Name) CancelAppButton
Location 171, 116
Size 75, 30
Text &Cancel
58 Module 1: Introducing Windows Forms

Tasks Additional information

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:

AcceptButton LogonButton • Practice: Creating a Form, in Module 1,


CancelButton CancelAppButton “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.
The following four steps (Steps 8, 9, 10, and 11) are not required to meet the objectives of the labs but are
required to run the application and view results.
8. Declare class member fields in the LoginForm Additional information is not necessary for this task.
class. Open the LoginFormCode.txt file, and copy
the code under the heading Declare these class
members in the LoginForm class.
9. Implement properties for the class. Open the Additional information is not necessary for this task.
LoginFormCode.txt file, and copy the code under
the heading Add these properties to the
LoginForm class.
10. Implement the Click event handler for the Cancel Additional information is not necessary for this task.
button. Open the LoginFormCode.txt file, and
copy the required code under the heading Create
a Click event handler for the Cancel button and
add the following code to the event handler.
Module 1: Introducing Windows Forms 59

Tasks Additional information

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.

Important In the InternalBusinessApp.sln project in \install_folder\Labfiles\Lab01_1\Ex02\Solution,


because the About Internal Business Application dialog box for the project is an inherited form, you
must build the solution before you can view the AppControlAboutForm form in Windows Forms
Designer.

Tasks Additional information

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

Tasks Additional information

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

Tasks Additional information

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.

You might also like