Beruflich Dokumente
Kultur Dokumente
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
70-316: Developing
and Implementing
Windows-Based Applications
with Microsoft Visual C#
.NET and Microsoft
Visual Studio .NET
■ Chapter 18 Introduction to Windows Forms
■ Chapter 19 User Interface Components
■ Chapter 20 Data in Windows Forms
■ Chapter 21 Web Services and COM
■ Chapter 22 Build Your Own Windows Control
■ Chapter 23 Deploying a Windows-Based App
■ Chapter 24 Security, Optimization and Everything Else
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:01:57 PM
Color profile: Generic CMYK printer profile
Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 /
Blind Folio 2
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:01:57 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
Introduction
to Windows Forms
CHAPTER
18
In this chapter, you will
• Discover how to create Windows Forms using visual inheritance
• Learn how to set properties on a form
• Become familiar with using controls
• Learn about delegates and event handlers
The .NET Framework provides many classes for building Windows applications, and
we will explore some of them in this chapter. In particular, we will spend time looking at
the System.Windows.Forms namespace, which is the cornerstone of application
development in Windows.
We will also introduce you to the application that we will use in this section of the
book to demonstrate Windows development. We will be creating a college registry data-
base application that keeps track of students, instructors, and courses. The application
will allow the user to interface with the back-end database. In this chapter, we will intro-
duce form design, place controls on our form, and react to the events that are generated.
Windows Forms
The .NET Framework has provided Windows developers with a new platform on which to
create applications—Windows Forms. By using this platform, developers can create Win-
dows applications, front-end interfaces for multiple-tiered applications, and front-end
interfaces for client applications. Anything that requires user intervention can be placed
inside a Windows Form. If you have just finished Part III of this book, you may be won-
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:01:57 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
However, sometimes the distinction is not as simple as in these examples. If you are
interested in learning more about the engineering of front-end applications, we suggest
that you find a book on design principles. The Microsoft exams are not going to test you
on whether you need to use a Windows Form or a Web Form. Since the two exams are
distinct and separate from each other, we have chosen to present the information for the
Windows exam in this part of the book (Part IV) and the web exam in Part III.
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:01:58 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
PART IV
User Controls A user control is an empty control from which other controls can be
built. To read more about user controls, see Chapter 22.
Forms A form is a type of control. It inherits from the Control class, so all
of the previous applies to forms as well. The Form class represents
a window or a graphical interface that can be displayed during an
application. Types of windows include dialog boxes, MDI (multiple
document interface) windows, and so on.
Components These classes do not derive from
System.Windows.Forms.Control; however, they need to be
included here since they provide visual features for your application.
For example, System.Windows.Forms.Menu is the base class for
classes such as MainMenu, MenuItem, and ContextMenu.
Common Dialog Boxes In order to achieve consistency between Windows applications, a
group of classes have been build that allow interaction with printing,
the file system, and so on. These are the common dialog boxes that are
displayed in an application when you select File | Open or File | Print
from the menus.
Containers A container can hold zero or more components. The Container
class is used when you want to group objects together. It is found in
System.ComponentModel.Container. A Form is an example
of a container that groups together controls such as buttons, text
boxes, and the like.
Table 18-1 Categories of Classes in Windows Forms
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:01:58 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
This is just a sampling of the hierarchy of classes within Windows Forms. A good exer-
cise would be to build a class relationship diagram in order to see where everything fits.
What Is a Form?
A form is the window that is used to present information to or accept information from
the end users. The form can be a simple window, an MDI (multiple document interface)
window, or a dialog box. We will look at each of these in this chapter.
Having said all that, one point to keep in mind at all times is that a form is actually an
object that is instantiated from a class. This means that a form exposes properties, meth-
ods, and events. The properties of a form allow you to set the look or appearance of the
form. You can set properties like the size, the background color, and so on. The methods
expose the behavior of the form—things like closing and activating. Events define the
interaction of the methods—such as loading and deactivating. We will explore the sig-
nificance of events later in the chapter.
Let’s look at the class from which a standard form is created. We will see later in this
chapter that you can create a form object using visual inheritance, a technique that allows
you to define the base class for your forms. However, for the purposes of this introduction
to forms, we will stick to a form that is created from the standard class. Figure 18-1 illus-
trates the class structure of the System.Windows.Forms namespace. Notice that a form
is really a type of control.
As this chapter progresses, we will be referring back to Figure 18-1. As you have
probably deduced, most of the prebuilt controls come from this namespace—buttons,
textboxes, and the like. We will be adding these controls to our form as the chapter
unfolds.
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:01:58 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
PART IV
Figure 18-1 Part of the System.Windows.Forms namespace
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:01:58 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
Figure 18-2
Our first
Windows Forms
program
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:01:59 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
TIP The Application class has many other methods that can be used to
manage an application. You could invoke Application.Exit() in order
to terminate a program in an orderly fashion. The remaining messages in the
message queue will be executed and then the application will terminate.
We can make our form more interesting by adding a button with the text “Hello
World!” on it.
using System;
using System.Windows.Forms;
using System.Drawing;
public class HelloWorldForm: Form
PART IV
{
private Button buttonHelloWorld;
public HelloWorldForm()
{
buttonHelloWorld = new Button();
buttonHelloWorld.Text = "Hello World!";
buttonHelloWorld.Left = 100;
buttonHelloWorld.Top = 100;
Controls.Add (buttonHelloWorld);
}
public static void Main()
{
Application.Run (new HelloWorldForm());
}
}
When we execute this program using csc HelloWorldForm.cs, we observe the form
as displayed in Figure 18-3.
In order to place a button on our form, we must first declare the existence of a button
reference:
Following good OOP guidelines, we then instantiate the button inside the form’s con-
structor. Once the button object is created, we can set the exposed properties of the but-
ton—Text, Left, and Top. These are just three of the properties that can be used. If
you want to see all of the properties, methods, and events that are available within the
Button class, be sure to look at the MSDN documentation within Visual Studio .NET.
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:01:59 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
Once the button is created and its properties are set, we then need to tell the construc-
tor to add the button to the list of controls that appear on our form:
Controls.Add (buttonHelloWorld);
This is accomplished by using the Controls collection and the Add() method. When
the constructor executes, our button object will be added to the form’s Controls col-
lection and made visible.
One other item of interest is how we have modified the Main() method of this ap-
plication. Instead of spreading the creation of our form object and the presentation of
the form over two lines of code, we have simply instantiated the form before passing it
as an argument to the Run() method. Since we have no need of the form object’s refer-
ence after the Run() method, there is no point in wasting cycles and memory space by
creating the object reference.
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:01:59 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
PART IV
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:01:59 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
Application.Run(new Form1());
Let’s add the button to our form and observe the extra code that is generated. Return
to the Form1.cs (Design) window by selecting its tab in the designer window. Select
the Button icon in the Toolbox and double-click it. That will place a button on your
form in its default location (top-left corner). You can move the button around by
selecting it on the form and dragging it to the position you want. Once the button is
Figure 18-6
Our first
Windows Forms
application
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:01:59 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
PART IV
Figure 18-7 The code window
selected on the form, you can change any of its properties by using the Properties
Explorer window (Figure 18-8).
When you press CTRL-F5 to execute the application, you will see a window similar to
the one we created through Notepad (refer back to Figure 18-3).
Look at the code window and the extra code that Visual Studio has placed in your
application (see Figure 18-9). Not a lot has changed except for the declaration of the
Button object. This is because our control has now been created and its properties set by
the design time of the development environment. In the coming sections, we will look at
this concept and compare it to the runtime manipulation of controls.
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:01:59 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:00 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
PART IV
Figure 18-9 Code generated from the Hello World button form
Figure 18-10
Our college
application
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:00 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
All-In-One
screen / MCAD/MCSD
/ MCSD Visual
Visual
C#C#
.NET
.NET
Certification
Certification
All-in-One
All-in-One
Exam
Exam
Guide
Guide
/ Rempel
/ Rempel
& Lind
& Lind
/ 222443-6
/ 222443-6
/ Chapter
/ Chapter
18
18
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:00 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
PART IV
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(192, 20);
this.textBox1.TabIndex = 2;
this.textBox1.Text = "";
//
// button1
//
this.button1.Location = new System.Drawing.Point(344, 200);
this.button1.Name = "button1";
this.button1.TabIndex = 3;
this.button1.Text = "E&xit";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(488, 421);
this.Controls.AddRange(new System.Windows.Forms.Control[]
{
this.button1, this.textBox1, this.label2, this.label1});
this.Name = "Form1";
this.Text = "HMR College";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
}
}
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:00 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
• VS .NET has added a fair bit of XML documentation comments to our code.
Refer back to Chapter 8 to see how these comments will be translated into XML
documentation.
• As we mentioned in the previous section, a Container object is required if
you need to group objects together. The Windows Forms Designer has created
an object reference of type Container in order to manage the components on
the form at run time:
private System.ComponentModel.Container components = null;
The object reference has been set to null at the start of the code. You may
wonder why this is necessary when we talked about a Controls collection
earlier in this chapter. However, consider that there may be elements in the
application that are not controls, and a Container object allows us to group
everything together. Our controls have been given reference variable names:
private System.Windows.Forms.Label label1;
TIP You may want to assign your controls meaningful names at the
beginning of the design. Notice how difficult it will be now to go back and
change the name of the label to something that represents its function, like
labelStudentName. The name can be changed in the Properties Explorer
window under Design.
• The Dispose() method is coded in order to perform any operations that are
necessary when garbage collection is done. Refer back to Chapter 2 to review
the concept of garbage collection. In this case, the Dispose() method is
called on the components object.
• In the InitializeComponent() method, the controls are instantiated and
are set to their initial behavior. Notice that the InitializeComponent()
method is called from the constructor. In this method, you will see the code
that is created by changing the properties in the Properties Explorer window.
Figure 18-11 shows the Properties Explorer for our title label.
• The Main() method is assigned as a single threaded apartment. This ensures
that drag and drop works properly and also allows the clipboard to function.
If you want to learn more about apartments and threading, read about threads
in MSDN.
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:00 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
PART IV
A Closer Look at Forms
Now that we’ve set the groundwork for developing forms, let’s explore some of the finer
details. In particular, we’ll look at the various properties, methods, and events that come
as part of the Form class. When we discuss methods and events, we will observe the
lifecycle of a form. Visual inheritance is another topic that warrants some discussion
here. Not only is visual inheritance covered on the exam, but it is a handy and time-sav-
ing method for creating forms.
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:01 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
Figure 18-12
Form Properties
and Methods
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:01 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
EXAM TIP You will find localization and globalization topics on the Microsoft
exam. Please refer to Chapter 7 for an introduction to the concepts and
Chapter 24 for the specifics of building localized Windows applications. You
will also find an introduction to localization of forms within this chapter.
Property Description
AcceptButton When you select this property, you are presented with a drop-down list
of buttons on your form. The button you choose will be the one that is
PART IV
“clicked” when the user presses the ENTER key.
AllowDrop If you are using drag and drop, you may want the form to receive
notification of a drag-and-drop activity. The property is set to False
by default.
BackColor This property specifies the color that will be used to display text and
graphics on the form.
CancelButton This is similar to the AcceptButton, except the button will be “clicked” if
the ESCAPE key is pressed.
ControlBox This property determines whether your form will display the standard
control box on the left of the title bar, indicating a menu that allows the
user to close, maximize, or minimize the window.
Font When you choose the font, it will be applied to the text on the form as
well as on any controls added to the form.
FormBorderStyle This property sets the appearance of the border of the form. By default,
it is set to Sizable. You can change it to FixedSingle, Fixed3D, FixedDialog,
FixedToolWindow, or SizeableToolWindow. Your choice depends on
your intention for the flexibility of the form.
Icon By changing the icon, you can set the icon file to be displayed in the
top-left corner of your form. It will also be the icon displayed when the
form is minimized.
Localizable This property will set whether localization can happen on your form.
When you select True, you can easily have the text of your form
displayed in a different language.
StartPosition When you set this property, you specify the position of the form when it
first appears on the screen.
Text By changing the Text property, you change the text on the title bar.
Table 18-2 Properties of a Form
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:01 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
Form Events
The first thing to happen to your form is the call to the constructor of the Form class by
using the keyword New(). Notice in the code generated by the Windows Forms
Designer that a call to the method InitializeComponent() is made in the con-
structor of the form. You can then place any of your initialization code in the
InitializeComponent() method.
Certain events are triggered (or fired) as a form is opened, closed, moved, and so on.
An event is caused by these actions, and these events create the lifecycle of the form. The
following are the key events, in order of appearance, that make up this lifecycle:
1. Load The Load event is fired just before the form is loaded into memory. The
event happens whenever a call is made to the Load() method or the Show()
method.
Figure 18-13 Using the Object Browser to explore the Form class
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:01 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
TIP The Dispose method is called automatically on the closing of the main
form. If you need to have termination code executed on the closing of any
other form, you must explicitly call Dispose().
PART IV
Method Description
Show() This method is actually inherited from the Control
class. It displays the form to the user.
Hide() This method is inherited from Control. As its name
suggests, it hides the form. However the form is still
in memory.
Close() This is a method of the Form class that closes the
form and releases its resources.
SetDesktopBounds(int, int, This method sets the boundaries of the form with
int, int) respect to the desktop coordinates.
SetDesktopLocation(int, int) This method provides the location of the form with
respect to the desktop coordinates.
Table 18-3 Methods of a Form
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:02 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
Visual inheritance can only be performed from within Visual Studio .NET. There are
two ways to implement it; the first way being the way we have used so far—deriving
your new form from an existing form.
The second way is by using the Inheritance Picker. From the menus, select File | Add
New Item. You will see the Add New Item dialog box displayed in Figure 18-14. Choose
Inherited Form from the right-hand pane. You will be presented with the Inheritance
Picker window (see Figure 18-15).
In the Inheritance Picker, find the form that you have stored as a base form (click on
the Browse button to search for it), and then click OK. This will cause a new form to be
created, and the code behind it will include something like this line, depending on
which form you picked:
In our case, we chose the first form that we created for our college application, and the
code demonstrates that the inheritance will be from Form (the original base class) to
Form1 (our template) to Form2 (the new form).
Figure 18-14
The Add New
Item dialog box
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:02 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
EXAM TIP Be sure to understand and work with both methods of creating a
form. Visual inheritance is a topic covered on the Windows exam.
Imagine the time you can save by implementing visual inheritance. The whole goal
PART IV
behind an object-oriented language is to eliminate duplication of effort. By creating a li-
brary of template forms and selecting them as base classes for your new applications,
you will reduce the amount of time you spend coding your application and can spend
more time on designing and testing.
Before we leave this subject, though, we must comment on the visual display of the
new form. Examine the form shown in Figure 18-16. This form was created via the In-
heritance Picker.
Notice the funny looking characters beside every control. These are called glyphs, and
when you select them, you see the border (as in Figure 18-16) that indicates that the con-
trol has been inherited. The color of the border will tell you what kind of security has been
applied to the control. Each level of access permissions shows a different shade of gray.
• Grey border with no sizing handles This means that the control is a
read-only control. You will notice from Figure 18-16 that the properties are
grayed out. You, as the user of the inherited control, cannot make any changes
to its properties. You will not be able to move or size it either. This occurs when
a control is specified with Private access modifiers.
• Standard border with sizing handles If a control is specified with either
Public or Protected modifiers, you will be able to size and move it.
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:02 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
project. Localization is the process of translating the resources of your application into a
different language.
In case you were starting to panic, there’s no need. To accomplish localization within
Visual Studio .NET, you do the following:
Let’s change our Hello World form to provide French and Spanish translations. Here
are the steps:
Figure 18-17 illustrates the effect of changing the button’s Text property for the
Spanish translation. Look under the Solution Explorer, and you will see additional
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:02 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
EXAM TIP The Windows exams will include a few questions on localizing
the form. Use this chapter as a starting point, and then refer to Chapter 7 for
an overall description.
The .NET Framework includes the Windows Forms Resource Editor (Winres.exe),
which helps you localize forms when you are using a third party to provide the localiza-
tion. Figure 18-18 demonstrates the Windows Resource Localization Editor window
that opens when you run Winres.exe from the command line.
If you’ve ever had to create multiple resource files in older versions of Visual Studio,
you will appreciate how simple it is in .NET to create applications that can be run on any
machine in any culture. For more information, refer to Chapter 7.
We will explore localization further when we discuss deploying our application in
Chapter 23. This section has just given you an indication of the power of the resources of
the .NET Framework.
PART IV
Controls
So far we have used a button and a text box on our form. In this section, we will explore
the different kinds of controls and their properties, methods, and events. By using the
right control in the right place, you can build an extremely effective graphical interface
for your users.
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:03 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
We will also introduce you to the generic elements of working with controls. In the
next chapter, we will broaden our discussion of controls and observe how some of
the more popular controls interact with the user.
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:03 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
Figure 18-19
The Toolbox
PART IV
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:03 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
• Double-click on the control in the Toolbox. This will create an instance of the
control on your form. It will be of its default size and position. You can then
click on the control’s handles to resize it or move it.
• Click once on the control in the Toolbox. When you move your mouse over to
the form, you will see a crosshair and a graphic representing your control. Click
on the form at the position of the top-left corner and drag until the control is
the desired size. By using this method, you have control over the position and
size of the control when you create its instance.
The Toolbox can be customized to accommodate your needs. Notice in Figure 18-19
that there is a tabbed list of the different types of controls. If you right-click anywhere on
the Toolbox, you will be presented with a menu from which you can choose Customize
Toolbox. The Customize Toolbox dialog box is illustrated in Figure 18-20.
NOTE The Customize Toolbox dialog box replaces the Components dialog
box from Visual Basic, and the Customize dialog box in prior versions of
Visual C++.
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:04 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
1. Create a reference variable for your control. You would usually make this a
private piece of data:
private Label myLabel;
2. Instantiate a new instance of the control.
Label myLabel = new myLabel();
3. Set the properties of the new control.
myLabel.Text = "This is my Label control.";
4. Add the new control to the form’s control collection.
this.Controls.Add (myLabel);
PART IV
5. Implement the event-handling code for the new control. We will explore event
handling later in this chapter.
Types of Controls
The following list categorizes controls by their function.
Let’s investigate the function of each control. Table 18-4 lists the popular controls
available in the Toolbox, along with descriptions of their functions. Figure 18-21 illus-
trates some of the different types of controls and their default sizes on the form. Notice
that some controls are not visible on the form—these controls show in the bottom pane
of the designer window.
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:04 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:04 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
PART IV
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:05 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
• Anchor Sets the location of the top-left corner of the container to which the
control is bound.
• Backcolor Sets the background color of the control.
• BackgroundImage Adds a background image to the control.
• Enabled Specifies whether the control is enabled or disabled (in which case
it is grayed-out).
• Focused Sets whether the control has focus (in which case it is the control in
the foreground).
• Font Sets the text properties.
• Left Sets the horizontal position of the top-left corner of the control.
• TabIndex Specifies the order of the controls. By default, TabIndex is set
when you add the control; however, you may want to change that order.
• Text Sets the text of the control.
• Top Sets the vertical position of the top-left corner of the control.
• Visible Determines whether the control is to be displayed or not.
In order to set a property of the control programmatically, use the reference variable
and the dot operator. In Visual Studio .NET, the dot operator will automatically present
you with a list of available properties—this is called IntelliSense and is a valuable tool
for the developer. You don’t have to worry about valid properties—they are listed for
you by IntelliSense. Figure 18-22 shows an example of this.
Figure 18-22
Using IntelliSense
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:05 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
Event Handling
So far we have avoided too much discussion about events in C# .NET for Windows
Forms. It’s time now to open this important topic and explore how events are dealt with
in the C# language. When you work with controls, you need to understand how to inter-
act with the events that can be triggered by user responses or system requirements.
What Is an Event?
An event is something that happens while the program is executing. It is a message that
is sent by a given object in order to inform the program that an action has occurred. It
can be generated by a user clicking on a button, pressing a key, moving a mouse, select-
ing a menu item, and so on. But it’s not just the user that can cause an event to happen.
The system may trigger an event (for example, when a file transfer is completed) or you
can force an event to occur within your program code.
PART IV
In an event-driven language such as C#, the application is essentially sitting there
waiting for events to happen. If a given event is triggered, the program responds with the
appropriate code written in the event handler. There is a direct relationship between the
sender of the event (whatever raised the event) and the handler of the event (the action
taken if the event occurs). However, keep in mind that while many events happen dur-
ing the course of an application’s life, you may only have code written for certain
events—this is normal.
Controls have events that are exposed to the developer and can be seen in the Object
Browser. They look like methods. However, when you are looking for events in Visual
Studio .NET, watch for the lightning bolt icon—this indicates that the item is an event.
You can see a list of events in the Properties Window by clicking on the lightning bolt.
The focus of this section of the chapter will be to deal with events, and this is called
event handling. We will look at the code that is written and talk about delegates, which are
commonly used classes for building event-handling routines. We will also return to this
discussion in the next chapter when we deal with individual controls.
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:05 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
Delegates
In C#, an event is made transparent by the use of delegates. The concept of a delegate is
roughly equivalent to the concept of function pointers in C and C++. The difference
between delegates and function pointers lies in the fully object-oriented, type-safe, and
secure qualities of a delegate. Not only that, but by using delegates, a developer can cre-
ate a reference to a method within a delegate object. A delegate object can also call the
method that it references. C# does not allow a target method (the method to be run
when the event is fired) to be assigned to an event, because the event has to pass parame-
ters to the method.
A delegate is a data structure that is derived from the Delegate class. By using dele-
gates, you can tie the actual method to an event at run time. A button is clicked, but the
button doesn’t know the method that needs to run, so it passes the event to the delegate
object, which is tied to the actual method required.
There are two parts to a delegate:
An event delegate includes two parameters that identify the source of the event and the
data that belongs to the event:
• Declare the delegate object. The signature of the delegate must match exactly
the signature of the method that is tied to the delegate.
• Create all the methods that match the signature of the delegate.
• Instantiate the delegate object and insert the methods.
• Use the delegate object and call the methods.
Let’s look at the code for using a delegate. Start by declaring the delegate object with
matching method signature:
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:05 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
Now for the finale. Call the methods through the delegate object:
PART IV
n();
n1();
In the next section, we will relate this technique to a process called event handling. By
employing event handling, we can respond to the events that are generated through the
user’s interaction with a control, through system events, or because of program-raised
events.
NOTE A single event handler (procedure) can be tied to multiple events. For
example, we could have a menu on this form with a menu item that simulates
the clicking of the button. In this case, we could invoke the same event handler.
If you look at the code generated by Visual Studio .NET in the Windows Forms
Designer section, you will see code that defines a new event handler:
This.button3.Click += new System.EventHandler (this.button3_Click);
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:05 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
Now for the easy part. Follow these steps to build the event-handler stub code:
TIP The parameter list includes a “sender” object (the originator of the
event) and an EventArgs object (which contains any information about
the event). In Chapter 19, we will look at this further.
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:06 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
Now, execute your program, click the button, and you will see the message box appear
as in Figure 18-24.
Event handlers can be added to your program at run time by adding a new
EventHandler object:
EXAM TIP Although all the work is done for you by Visual Studio .NET
when you double-click on the control (the stubbed event handler is created
for you), you will need to understand the process as we described it earlier in
PART IV
this chapter.
You can see how easy this is inside Visual Studio .NET. A lot of coding is done for you.
Your role is to simply add the program logic. That’s the goal of Rapid Application Devel-
opment (RAD). It frees the developer to concentrate on the purpose of the application
and does a lot of the background grunt work for you.
Figure 18-24
Result of
the button’s
Click event
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:06 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
Summary
This chapter has been an introduction to the exciting world of Windows development.
In particular, this chapter has made us familiar with working with Windows Forms.
However, there is so much more to it than what we’ve looked at here. In the coming
chapters, we will go into the details of using controls. We will also investigate creating
our own controls. In the next chapter, you will be introduced to the entire application
for our college. We will dissect this application, and by doing so, come to understand
how to work with back-end SQL data, learn how to validate input from the user, investi-
gate using services, and finally be able to deploy our final application.
Unless the visual programming world changes drastically (and, if you are a seasoned
developer, you know this is possible), you will always find yourself building Windows
applications. The web interface is wonderful for many reasons, including platform inde-
pendence, but eventually you need the rich and consistent look of a Windows applica-
tion. You may also need to write applications that have access to local resources, and
this may not be possible with a Web Form. So get your typing fingers ready and let’s
delve deeper into the world of Windows applications.
Test Questions
1. Which of the following methods are ways to create a Windows Form?
A. Visual inheritance.
B. Building a derived class from System.Windows.Forms.Form.
C. Extending a prebuilt form.
D. Selecting a form class from the Inheritance Picker.
E. All of the above.
2. Select the reasons why you would use Windows Forms over Web Forms.
A. You need the processing to occur on the server.
B. You need the processing to occur on the client.
C. You need access to local resources.
D. You need a consistent graphical interface.
E. You need platform independence.
3. Select the line of code that will create a new form.
A. Form.MyForm m = new MyForm();
B. System.Window.Forms.Form MyForm m =
new System.Window.Forms.Form();
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:06 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
PART IV
B. CheckedListBox
C. CheckBox
D. ListBox
E. RadioButton
5. What is the output from the following code segment?
using System;
using System.Windows.Forms;
public class MyForm: Form
{
private Button MyButton;
public MyForm()
{
IntializeComponent();
}
private void InitializeComponent()
{
this.MyButton = new Button();
this.MyButton.Text = “Hello World!”;
this.MyButton.Click += new System.EventHandler(this.MyButton.Click);
}
public static void Main()
{
MyForm m = new MyForm();
Application.Run(m);
}
}
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:06 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:07 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
PART IV
C. The property asks you for the translation language.
D. The program prompts you to provide a language resource.
8. By setting the Text property on the form, you will cause the value of the Text
property to display on which part of the form?
A. Bottom-right corner
B. Top-right corner
C. Title bar
D. Status bar
9. What causes the following Load event to fire? Assume that the form is the only
form in the application.
private void Form1_Load (object sender, System.EventArgs e)
{
Form1.Hide();
}
A. The user starts the application.
B. The Show() method is called.
C. The user ends the application.
D. A call is made to Form1_Load from another method.
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:07 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
18
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:07 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
18
Test Answers
PART IV
1. E.
2. B, C, and D.
3. D.
4. C.
5. D. Program does not compile. The error message states that there is a missing
event handler.
6. A.
7. A.
8. C.
9. A and B. The user starts the application or a call is made to the Show()
method.
10. A. The application will not compile because the Form1_Load method would
need a reference variable to the actual form.
11. C.
12. B.
13. B. Deactivate(). It is an event not a method.
14. C.
15. D.
P:\010Comp\All-in-1\443-6\ch18.vp
Friday, August 23, 2002 5:02:07 PM