+ All Categories
Home > Documents > 1_Windows Forms Creation With C# 2005

1_Windows Forms Creation With C# 2005

Date post: 15-Oct-2014
Category:
Upload: dayooyefuga
View: 281 times
Download: 1 times
Share this document with a friend
161
Windows Forms Creation and Configuration with C# 2005 -Dayo Oyefuga
Transcript
Page 1: 1_Windows Forms Creation With C# 2005

Windows Forms Creation and Configuration with C# 2005

-Dayo Oyefuga

Page 2: 1_Windows Forms Creation With C# 2005

Basic Windows Forms Creation

Learning objective

After completing this topic, you should be able to identify how to create a basic Windows form with controls.

1. Creating and customizing forms

In C# 2005, Windows Forms are a core unit of the design platform for Windows application development.

In a Windows Forms project, a form is a component that groups – or contains – the objects that enable interaction between users and an application.

Once you've created a form, you can add controls, other components, and custom code to it, to enable its functionality.

Controls are objects you can add to a form that have a user interface – you can see and interact with them when you run an application.

Controls are a type of component – but other sorts of components can also provide functionality without having a user interface. When you add these sorts of components to a form, it displays only at design time, in a component tray at the bottom of the Design window.

You can add controls and components either at design time or – through programming – dynamically at runtime.

At design time, you can add controls and components directly to a form in Design view, by double-clicking them in the Toolbox or dragging them from the Toolbox onto a form.

The Integrated Development Environment (IDE) automatically generates initialization code for the controls or components. You then need to create any code that sets the controls or components to perform custom actions.

Types of controls and components you can add to a form include

command controls and components

text edit controls

text display controls

value-setting controls

date-setting controls

list selection controls

command controls and components

Page 3: 1_Windows Forms Creation With C# 2005

Command controls perform some sort of action and are added to the main page of the

Form. Components are added to the component tray rather than the Form. Examples of

command controls in Visual Studio 2005 are

the Button control, which creates a button that starts or stops a specific process when clicked

the NotifyIcon component, which displays a status notification icon on the user's taskbar

text edit controls

Text edit controls enable you to accept user input. Examples of text edit controls you can

add in Visual Studio 2005 are

the TextBox control, which displays an area for users to enter text when an application runs

the MaskedTextBox control, which creates a specific format in which users can enter text on a form

the RichTextBox control, which creates a specific format in which text can be interpreted from .rtf

or .txt files and displayed, such as bold or italics

text display controls

Text display controls enable you to display text on a form. Examples of text display

controls you can add in Visual Studio 2005 are

the Label control, which displays text

the LinkLabel control, which displays a link users can click to connect to a web site

value-setting controls

Value-setting controls display certain clickable items on a form, to enable users to select

options or values. Examples of value-setting controls you can add in Visual Studio 2005

are

the CheckBox control, which adds a label and accompanying checkbox whose value can be set to

true or false on a form

the RadioButton control, which adds a label radio button to a form; radio buttons are most often

used in groups to present mutually exclusive selections

the TrackBar control, which adds an adjustable scale to a form

date-setting controls

Date-setting controls enable users to choose dates or times from items on a form.

Examples of date-setting controls you can add in Visual Studio 2005 are

the MonthCalendar control, which enables a user to select a range of dates from a calendar

the DateTimePicker control, which enables a user to select a specific date or time from a calendar

and to specify a date or time format

list selection controls

List selection controls display clickable lists of available items in a form. Examples of list

selection controls you can add in Visual Studio 2005 are

the ListBox control, which displays items in a static, clickable list

Page 4: 1_Windows Forms Creation With C# 2005

the ComboBox control, which displays items in a clickable drop-down list, and enables users to enter

text or select from the list to specify a choice of item

the CheckedListBox control, which displays a list of items with a checkbox next to each item

Suppose you want to create a new Windows Forms project and then add a Button control to it. When a

user clicks the button at runtime, the application must add a TextBox control to the form dynamically.

So you open the New Project dialog box.

In the New Project dialog box, you select Windows Application in the Templates pane.

You type the name of the application – MyWindowsForm in this case – in the Name text box, and click

OK.

The project you've created opens and a blank form – named Form1.cs by default – displays in Design view.

You use the Toolbox to add a Button control directly to the form.

You double-click Button in the Toolbox.

A new button – named Button1 by default – displays on the form. Visual Studio automatically adds all

controls to the top-left corner of the form.

You drag and drop the control to position where it is required on the form.

Now you need to configure the Button control in the code editor. You want to add a reference to your

control variable, set the control's location, and add the control.

So you double-click the control, which creates the default subroutine for handling its Click event.

public class Form1{

private void Button1_Click(object sender, System.EventArgs e) {

}}

You can now add to the code to customize the button's functionality – in this case, to configure it to add a TextBox control dynamically. To do this, you code its Click event handler to specify what must occur

when the button is clicked.

Page 5: 1_Windows Forms Creation With C# 2005

public class Form1{ private void Button1_Click(object sender, System.EventArgs e) {

}}

You first declare an instance of your TextBox control and initialize it.

TextBox MyText = new TextBox();

And you set the control's location.

MyText.Location = new Point(25, 25);

Once you've created your control instance and set its location, you access your form's ControlCollection. The ControlCollection resides in a property within the Form class named

Controls, and contains all controls for your form.

Calling the Add method of ControlCollection, you add your TextBox control to the form.

public class Form1{ private void Button1_Click(object sender, System.EventArgs e) { TextBox MyText = new TextBox(); MyText.Location = new Point(25, 25); this.MISSING CODE; }}

You type Controls.Add(MyText) to complete the code.

You have now added the control to your form.

public class Form1{ private void Button1_Click(object sender, System.EventArgs e) { TextBox MyText = new TextBox(); MyText.Location = new Point(25, 25); this.Controls.Add(MyText);

Page 6: 1_Windows Forms Creation With C# 2005

}}

Note You can use the Properties window to set the display – or visual – properties of the button.

Next you want to add a component that will display a status notification icon in the taskbar when you run the application.

So you double-click NotifyIcon in the Toolbox.

A new NotifyIcon component – named NotifyIcon1 by default – displays in a component tray,

below the form.

Once you've opened the Properties window, you can configure the value of the component's Icon

property. To specify which icon the component must display on the user's taskbar at runtime, you set the path to the icon as the value of the component's Icon property.

To do this, you click the ... (ellipses) button in the Icon text box.

The Open dialog box appears, defaulting to a location on your file system. Here you navigate to the location of your icon.

In this case, it resides just off the default location, so you select the icon, App.ico, and click Open.

You have configured the value of the component's Icon property.

Question

When a user clicks a button you've named Button1, you want the application

you're designing to add another Button control named MyButton to a form.

You've already declared a variable for the new Button control and specified its

required location.

Complete the code you use to add the MyButton control.

public class Form1{ private void Button1_Click(object sender, System.EventArgs e) { Button MyButton = new Button(); MyButton.Location = new Point(15, 10); this.MISSING CODE;

Page 7: 1_Windows Forms Creation With C# 2005

}}

Answer

To add the MyButton control, you type

Controls.Add(MyButton);

2. Viewing form initialization code

When you add controls to a form and manipulate them in Design view, code for initializing the form and its controls – including default properties that specify how they must display at runtime – is generated automatically.

To view this code for a form, you access its InitializeComponent method in the Visual Studio 2005

code editor.

If necessary, you can use the code editor to make changes directly to a form's InitializeComponent

method. However, it's preferable to make changes in Design view because small errors you introduce could cause an application to behave unexpectedly or fail to compile.

You can copy the initialization code for a form and paste it into a new form, to add the same set of controls and components – including their configuration settings – to the new form automatically.

Suppose you've added a new form named Form2.cs to a Windows Forms application. To the form, you've added various controls. You now want to view the code that will initialize the form and the controls you've added.

To do this, you first open the code editor for the form by selecting View - Code.

Note You can also open the code editor by double-clicking the form.

The code editor provides Class Name and Method Name drop-down lists, to enable you to navigate project code.

To access the code that initializes the form and its controls, you select the form and the appropriate method.

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;

Page 8: 1_Windows Forms Creation With C# 2005

using System.Windows.Forms;

namespace MyWindowsForm{ public partial class Form2 : Form { public Form2() { InitializeComponent(); }

private void Form2_Load(object sender, EventArgs e) {

} }}

You select MyWindowsForm.Form2 from the Class Name drop-down list, and select InitializeComponent() from the Method Name drop-down list.

The code for the form's InitializeComponent method displays on a new tabbed page.

internal partial class Form2 : System.Windows.Forms.Form{

//Form overrides dispose to clean up the component list. internal Form2() { InitializeComponent(); } [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool disposing) { if (disposing && components != null) { components.Dispose(); } base.Dispose(disposing); }

//Required by the Windows Form Designer private System.ComponentModel.IContainer components;

//NOTE: The following procedure is required by the Windows Form Designer

Page 9: 1_Windows Forms Creation With C# 2005

//It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent(){ this.TextBox1 = new System.Windows.Forms.TextBox(); this.Label1 = new System.Windows.Forms.Label(); this.LinkLabel1 = new System.Windows.Forms.LinkLabel(); this.DateTimePicker1 = new System.Windows.Forms.DateTimePicker(); this.CheckBox1 = new System.Windows.Forms.CheckBox(); this.ComboBox1 = new System.Windows.Forms.ComboBox();

You scroll down to view the code that initializes individual controls on the form.

The first few lines of code in the InitializeComponent subroutine initialize the controls you've added

to the form.

private void InitializeComponent(){ this.TextBox1 = new System.Windows.Forms.TextBox(); this.Label1 = new System.Windows.Forms.Label(); this.LinkLabel1 = new System.Windows.Forms.LinkLabel(); this.DateTimePicker1 = new System.Windows.Forms.DateTimePicker(); this.CheckBox1 = new System.Windows.Forms.CheckBox(); this.ComboBox1 = new System.Windows.Forms.ComboBox(); this.SuspendLayout(); // //TextBox1 // this.TextBox1.Location = new System.Drawing.Point(100, 16); this.TextBox1.Name = "TextBox1"; this.TextBox1.Size = new System.Drawing.Size(100, 20); this.TextBox1.TabIndex = 0; // //Label1 // this.Label1.AutoSize = true; this.Label1.Location = new System.Drawing.Point(12, 23); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(39, 13); this.Label1.TabIndex = 1; this.Label1.Text = "Label1"; //

Page 10: 1_Windows Forms Creation With C# 2005

//LinkLabel1 //

Subsequent code in the subroutine sets the specific properties that each control must have when the form is opened at runtime. These properties are determined by how you've placed or configured the controls in Design view, or assume default values.

Instead of switching back to Design view and using the Properties window or resizing controls on the form to get them perfect, you can adjust the property values directly in the code.

Each control has several basic properties, four of which are common to most controls:

Location

Name

Size

TabIndex

Location

The Location property determines the position of the control in relation to the top-left

corner of the form. Its value is an instance of the Point structure that resides in the

System.Drawing namespace, whose overloaded constructor can take in two Int32

values that determine the control's location, in pixels on the form. These numbers reflect

the X-axis and Y-axis in relation to the top-left corner of the form. This is the syntax for the Location property:

this.control.Location = new System.Drawing.Point(x-axis, y-axis);

Name

The Name property is used by the application to identify a control. This is the syntax for the

Name property:

this.control.Name = "name";

Size

The Size property determines how big the control is in pixels. The Size property uses the

Size structure of the System.Drawing namespace, whose overloaded constructor can

take in two Int32 values. These values determine the control's actual size in pixels,

representing the control's width and height. This is the syntax for the Size property:

this.control.Size = new System.Drawing.Size(width, height);

TabIndex

The TabIndex property determines focus controls have based on pressing the tab key.

For example, if the TabIndex property of a control is set to 0, that control automatically

Page 11: 1_Windows Forms Creation With C# 2005

has focus when the form opens. The first time tab is pressed, focus shifts to whichever control has the TabIndex value of 1. When the maximum given value of TabIndex is

reached, focus returns to the control with the lowest value. The TabIndex value should be

unique for each control on the form. The TabStop property can be used to enable or

disable tab focus. This is the syntax for the TabIndex property:

this.control.TabIndex = index;

Apart from the basic properties applied to each control, some controls have additional common properties.

For example, the Label control has

an AutoSize property, which enables the control to resize automatically to fit its contents

a Text property, which displays the text associated with the control

private void InitializeComponent(){ this.TextBox1 = new System.Windows.Forms.TextBox(); this.Label1 = new System.Windows.Forms.Label(); this.LinkLabel1 = new System.Windows.Forms.LinkLabel(); this.DateTimePicker1 = new System.Windows.Forms.DateTimePicker(); this.CheckBox1 = new System.Windows.Forms.CheckBox(); this.ComboBox1 = new System.Windows.Forms.ComboBox(); this.SuspendLayout(); // //TextBox1 // this.TextBox1.Location = new System.Drawing.Point(100, 16); this.TextBox1.Name = "TextBox1"; this.TextBox1.Size = new System.Drawing.Size(100, 20); this.TextBox1.TabIndex = 0; // //Label1 // this.Label1.AutoSize = true; this.Label1.Location = new System.Drawing.Point(12, 23); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(39, 13); this.Label1.TabIndex = 1; this.Label1.Text = "Label1"; // //LinkLabel1 //

Page 12: 1_Windows Forms Creation With C# 2005

The LinkLabel control has a TabStop property that specifies whether the control is able to get tab

focus.

//LinkLabel1 // this.LinkLabel1.AutoSize = true; this.LinkLabel1.Location = new System.Drawing.Point(12, 54); this.LinkLabel1.Name = "LinkLabel1"; this.LinkLabel1.Size = new System.Drawing.Size(59, 13); this.LinkLabel1.TabIndex = 2; this.LinkLabel1.TabStop = true; this.LinkLabel1.Text = "LinkLabel1"; // //DateTimePicker1 // this.DateTimePicker1.Location = new System.Drawing.Point(15, 132); this.DateTimePicker1.Name = "DateTimePicker1"; this.DateTimePicker1.Size = new System.Drawing.Size(200, 20); this.DateTimePicker1.TabIndex = 4; // //CheckBox1 // this.CheckBox1.AutoSize = true; this.CheckBox1.Location = new System.Drawing.Point(15, 109); this.CheckBox1.Name = "CheckBox1"; this.CheckBox1.Size = new System.Drawing.Size(81, 17); this.CheckBox1.TabIndex = 3; this.CheckBox1.Text = "CheckBox1"; this.CheckBox1.UseVisualStyleBackColor = true; //

The CheckBox control has a UseVisualStyleBackColor property that determines the background

style.

this.LinkLabel1.Text = "LinkLabel1"; // //DateTimePicker1 // this.DateTimePicker1.Location = new System.Drawing.Point(15, 132); this.DateTimePicker1.Name = "DateTimePicker1"; this.DateTimePicker1.Size = new System.Drawing.Size(200, 20); this.DateTimePicker1.TabIndex = 4; //

Page 13: 1_Windows Forms Creation With C# 2005

//CheckBox1 // this.CheckBox1.AutoSize = true; this.CheckBox1.Location = new System.Drawing.Point(15, 109); this.CheckBox1.Name = "CheckBox1"; this.CheckBox1.Size = new System.Drawing.Size(81, 17); this.CheckBox1.TabIndex = 3; this.CheckBox1.Text = "CheckBox1"; this.CheckBox1.UseVisualStyleBackColor = true; // //ComboBox1 // this.ComboBox1.FormattingEnabled = true; this.ComboBox1.Location = new System.Drawing.Point(15, 199); this.ComboBox1.Name = "ComboBox1"; this.ComboBox1.Size = new System.Drawing.Size(121, 21); this.ComboBox1.TabIndex = 5; //

And the ComboBox control has a FormattingEnabled property that allows contained collection

properties – known as DisplayMembers – to be displayed with a chosen formatting.

Question

Suppose you've added a TextBox control to a form. You now want to add code to

the InitializeComponent subroutine for the form to set how large the control

is in pixels.

Which line of code does this?

//TextBox1 // this.TextBox1.Location = new System.Drawing.Point(100, 16); this.TextBox1.Name = "TextBox1"; this.TextBox1.Size = new System.Drawing.Size(100, 20); this.TextBox1.TabIndex = 0;

Options:

1. this.TextBox1.Location = new System.Drawing.Point(100, 16);

2. this.TextBox1.Size = new System.Drawing.Size(100, 20);

3. this.TextBox1.TabIndex = 0;

Page 14: 1_Windows Forms Creation With C# 2005

Answer

To determine how big the control is in pixels, you use the code

this.TextBox1.Size = new System.Drawing.Size(100, 20);

Option 1 is incorrect. This code sets the position of the control as it will appear on the form rather than determining the size of the control.

Option 2 is correct. This control sets the size of the control on the form to 100 by 20 pixels.

Option 3 is incorrect. This code sets the tab order of the control, rather than determining its size.

Question

Suppose you have added a Label control to your Windows form. You want to write code to ensure the control will adjust itself to fit any text added to the control.

Which line of code does this?

//Label1 // this.Label1.AutoSize = true; this.Label1.Location = new System.Drawing.Point(12, 23); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(39, 13); this.Label1.TabIndex = 1; this.Label1.Text = "Label1";

Options:

1. this.Label1.AutoSize = true;

2. this.Label1.Name = "Label1";

3. this.Label1.Text = "Label1";

Answer

To ensure that the control will automatically adjust its size to fit any text added to it, you use the code

this.Label1.AutoSize = true;

Page 15: 1_Windows Forms Creation With C# 2005

Option 1 is correct. This code sets the control to automatically resize itself to fit its contents.

Option 2 is incorrect. This code determines the name of the control that is used to identify it on the form.

Option 3 is incorrect. This code displays the text associated with the control on the form. If this text runs longer than the label's set horizontal size or requires more vertical space than is given, not all of the text will be seen.

3. Adding controls at runtime

Instead of adding controls to a form at design time, you can choose to add controls to a form dynamically at runtime.

To do this, you include code that will create a control at runtime in any appropriate event handler.

The properties you configure for a control in this way are similar to those that you customize in Design view and in the InitializeComponent subroutine for a form. However, the .NET Framework 2.0

supports many different controls requiring or providing different configuration options to be set.

Suppose you want to develop a method that creates a new DateTimePicker control and initializes it.

You can then call this method from any event handler, such as the handler for the Form's Load event.

In the code editor for the form, you begin by instantiating a new DateTimePicker control.

public class Form3{ public void CreateNewDateTimePicker() { DateTimePicker DateTimePicker1 = new DateTimePicker(); }}

Properties you can configure for the DateTimePicker control include

MinDate – the earliest date users can select

MaxDate – the latest date users can select

CustomFormat – a string used to set the format for the date and time used in the control

ShowUpDown – a setting that displays the control as a spin box rather than as a drop-down list

Next you set the required properties of the control. In this case, you want the control to enable users to choose a date anywhere between October 5, 2004 and the current date. So you set the minimum and maximum dates for the control.

Page 16: 1_Windows Forms Creation With C# 2005

public class Form3{ public void CreateNewDateTimePicker() { DateTimePicker DateTimePicker1 = new DateTimePicker(); MISSING CODE = new System.DateTime(2004, 10, 05); DateTimePicker1.MaxDate = DateTime.Today; }}

You type DateTimePicker1.MinDate to complete the code that sets the earliest date users must be

able to select.

You have now set the required minimum and maximum dates for the DateTimePicker control. For the

maximum date, you have used DateTime.Today, which is a shared property that accesses a

DateTime structure set to the current date by using the system clock on the local machine.

public class Form3{ public void CreateNewDateTimePicker() { DateTimePicker DateTimePicker1 = new DateTimePicker(); DateTimePicker1.MinDate = new System.DateTime(2004, 10, 05); DateTimePicker1.MaxDate = DateTime.Today; }}

Then you set a custom format string, specifying the full month name followed by the double-digit day, followed by a comma and then the year, after which is a dash and the name of the day of the week. You then indicate to your control that you are customizing the format of its options.

DateTimePicker1.CustomFormat = "MMMM dd, yyyy - dddd"; DateTimePicker1.Format = DateTimePickerFormat.Custom; }}

To complete the control's unique configuration, you display the control as a spin box control. You can then go on to specify its more common properties such as Location and Size, as well as add it to the

form's control collection.

DateTimePicker1.ShowUpDown = true;

Page 17: 1_Windows Forms Creation With C# 2005

}}

Now suppose you want to develop a method that creates a new NotifyIcon component and initializes

it.

In the code editor for the form, you instantiate a new NotifyIcon component.

public class Form3{ public void CreateNewDateTimePicker() { DateTimePicker DateTimePicker1 = new DateTimePicker(); DateTimePicker1.MinDate = new System.DateTime(2004, 10, 05); DateTimePicker1.MaxDate = DateTime.Today; DateTimePicker1.CustomFormat = "MMMM dd, yyyy - dddd"; DateTimePicker1.Format = DateTimePickerFormat.Custom; DateTimePicker1.ShowUpDown = true; }

public void CreateNewNotifyIcon() { NotifyIcon NotifyIcon1 = new NotifyIcon();

}}

Next you set the required properties of the control. In this case, when a user hovers their mouse over the icon, you want the control to display the text "Click Me".

public class Form3{ public void CreateNewDateTimePicker() { DateTimePicker DateTimePicker1 = new DateTimePicker(); DateTimePicker1.MinDate = new System.DateTime(2004, 10, 05); DateTimePicker1.MaxDate = DateTime.Today; DateTimePicker1.CustomFormat = "MMMM dd, yyyy - dddd"; DateTimePicker1.Format = DateTimePickerFormat.Custom; DateTimePicker1.ShowUpDown = true; }

public void CreateNewNotifyIcon() { NotifyIcon NotifyIcon1 = new NotifyIcon();

Page 18: 1_Windows Forms Creation With C# 2005

MISSING CODE = "Click Me"; }}

You type NotifyIcon1.Text to complete the code.

You have now set the required Text property for the NotifyIcon component.

public class Form3{ public void CreateNewDateTimePicker() { DateTimePicker DateTimePicker1 = new DateTimePicker(); DateTimePicker1.MinDate = new System.DateTime(2004, 10, 5); DateTimePicker1.MaxDate = DateTime.Today; DateTimePicker1.CustomFormat = "MMMM dd, yyyy – dddd"; DateTimePicker1.Format = DateTimePickerFormat.Custom; DateTimePicker1.ShowUpDown = true; }

public void CreateNewNotifyIcon() { NotifyIcon NotifyIcon1 = new NotifyIcon(); NotifyIcon1.Text = "Click Me";

Finally, you specify that the control must be visible on the user interface.

NotifyIcon1.Visible = true; } }

It is possible to configure more complex controls in this manner such as list selection controls such as ListBox. Here we can write a subroutine initializing a Listbox, allow users to select more than one of

the items in its list through its SelectionMode property, and then add items to its list by manipulating its

Items collection. You must pause painting of the control while this happens by calling BeginUpdate

and EndUpdate.

public class Form3{ public void CreateNewDateTimePicker() { DateTimePicker DateTimePicker1 = new DateTimePicker(); DateTimePicker1.MinDate = new System.DateTime(2004, 10, 5);

Page 19: 1_Windows Forms Creation With C# 2005

DateTimePicker1.MaxDate = DateTime.Today; DateTimePicker1.CustomFormat = "MMMM dd, yyyy – dddd"; DateTimePicker1.Format = DateTimePickerFormat.Custom; DateTimePicker1.ShowUpDown = true; }

public void CreateNewNotifyIcon() { NotifyIcon NotifyIcon1 = new NotifyIcon(); NotifyIcon1.Text = "Click Me"; NotifyIcon1.Visible = true; }

public void IBMethod() { ListBox myLb = new ListBox(); myLb.SelectionMode = SelectionMode.MultiSimple; myLb.BeginUpdate(); myLb.Items.Add("Item 1"); myLb.Items.Add("Item 2"); myLb.Items.Add("Item 3"); myLb.EndUpdate(); }}

Question

Suppose you want to create a DateTimePicker control that will display at

runtime. You want to set the maximum date for a control you added to your Windows form that will enable users to select a specific date or time from a calendar on a Windows form.

Complete the code to do this.

public class Form3{ public void CreateNewDateTimePicker() { DateTimePicker DateTimePicker1 = new DateTimePicker(); DateTimePicker1.MinDate = new System.DateTime(2004, 10, 5); MISSING CODE = DateTime.Today; }}

Page 20: 1_Windows Forms Creation With C# 2005

Answer

To set the maximum date for the control, you type

DateTimePicker1.MaxDate

Summary

You can add controls, components, and code to a Windows form in C# 2005. The types of controls you can add to a form are command, text edit, text display, value-setting, date-setting, and list selection controls.

One way to add controls to a form is in design time by selecting them from the Toolbox and placing them on the form. You can view the properties of each control in the InitializeComponent method window

in the form's code editor. However, you shouldn't adjust the properties on this window as this may cause your application to crash.

Another way to add controls to a Windows form is at runtime. You can do this by specifying a particular event and methods for a control in the form's code editor.

Control and Layout Enhancement in Windows Forms

Learning objective

After completing this topic, you should be able to identify how to configure controls and layout of Windows forms.

1. Setting access keys

Visual Studio 2005 provides various tools that help to make designing forms consistent and easier.

System.Windows.Forms.Form is the main class used in designing Windows forms in Visual Studio

2005. This class contains various new members that cover access, layout, appearance, and accessibility properties.

Access keys provide shortcuts for buttons and menu items on a Windows form.

An access key is represented by an underlined character in the text of a menu item or on a button. To use an access key at runtime, users can press the Alt key on their keyboard plus the underlined character when they want to select the item on the form.

Page 21: 1_Windows Forms Creation With C# 2005

Suppose you've added a Button control to a form and – using the Properties window – set the control to

display the text "Print." You now want to set the letter "P" in the text as an access key.

You type & immediately before the "P" in the Text text box of the Properties window, and press Enter.

An underscore now marks the "P" character on the Print button on the form, to indicate that it's an access key.

Question

Suppose you have created a new Windows form and added a Button control to

the form. You've set the button to display the text "Exit." Now you want to create an access key using the "x" character in the button text.

Which series of steps do you take to create an access key for the Exit button?

Options:

1. Type & between the "E" and the "x" in the Text text box, and press Enter

2. Type & in the Text text box

3. Type # in the Text text box and press Enter

Answer

To create an access key for the Exit button, you type & between the "E" and the

"x" in the Text text box, and press Enter.

2. Configuring form layout and appearance

The properties you can use to customize the appearance and layout of Windows forms are

FormBorderStyle

Margin

Padding

Dock

FormBorderStyle

The FormBorderStyle property of a form enables you to control a form's resizing

behavior and its appearance by changing its border styles. By default, the FormBorderStyle property is set to Sizeable, which means that the form can be

resized as per user's requirements. You can also set the form's border style to FixedSingle to prevent the form from being resized at runtime.

Margin

Page 22: 1_Windows Forms Creation With C# 2005

The Margin property of a control ensures that all controls on a form are kept a certain

distance away from other controls' borders by setting margins. By default, the Margin

property is set to 3, which means that a control has a 3-pixel margin from other controls.

You can set a control's Margin property to any other number to adjust this margin

distance.

Padding

The Padding property of a control ensures that a control's content is kept a certain

distance away from that control's borders by setting padding. By default, the Padding

property is set to 0, which means that no padding is assigned to the control. You can set

the control's Padding property to any other number of pixels to adjust padding distance.

The AutoSize property of a control should be enabled before you can set the Padding

property.

Dock

The Dock property of a control specifies the location of a control on a form relative to its

borders and thus enables you to control form alignment . By default, the Dock property is

set to None, signifying that there is no set associated location. You can also set this

property to Left, Right, Top, or Bottom. You can also set it to Fill, to have the control

take up the entirety of the form.

Suppose you've created a Windows form named "DialogBox" and added Label, TextBox, and Button

controls to the form.

To configure the layout and appearance of the form, you now want to

set a border style for the form

configure the margins for the TextBox and Label controls

set appropriate padding for the TextBox and Label controls

align the Button control to the edges of the form

In the class for the form, you set the FormBorderStyle property of the form to the appropriate value, to

present a dialog style border that cannot be resized at runtime.

public class Form5{ private void Form5_Load(object sender, System.EventArgs e) { this.FormBorderStyle = Windows.Forms.FormBorderStyle.MISSING CODE;

}}

Page 23: 1_Windows Forms Creation With C# 2005

You type FixedDialog to complete the code.

You have completed the code to set the border style of your form.

public class Form5{ private void Form5_Load(object sender, System.EventArgs e) { this.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedDialog;

}}

After you've set the required border style for the form, you return to Design view.

Next you want to change the margin settings for the TextBox and Label controls, to ensure that these

controls are kept a certain distance away from each other's borders. To do this, you configure the appropriate settings using the Properties window.

To set the Properties window to display the properties of the Label control, you select the control on the

form.

In the Properties window, you then expand the Margin node, to view the current margin settings for the control.

In this example, you want to set all margins for the Label control to the same value – 25 pixels.

You type 25 in the All text box in the Properties window, and press Enter.

You have now set all the Margin property values for the Label control to the same value.

To apply the same margin settings for the TextBox control, you select the control on the form, expand

the Margin node in the Properties window, type 25 in the All text box, and press Enter.

To access the code for designer, you view the code contained in Form5.Designer.cs, where Form5 is the name of your form.

In the form's InitializeComponent method, the code for initializing the Label and TextBox controls

now includes the margin settings you specified using the Properties window in Design view.

//Label1 // this.Label1.AutoSize = true;

Page 24: 1_Windows Forms Creation With C# 2005

this.Label1.Location = new System.Drawing.Point(25, 41); this.Label1.Margin = new System.Windows.Forms.Padding(25); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(35, 13); this.Label1.TabIndex = 3; this.Label1.Text = "Name"; // //TextBox1 // this.TextBox1.Location = new System.Drawing.Point(110, 34); this.TextBox1.Margin = new System.Windows.Forms.Padding(25); this.TextBox1.Name = "TextBox1"; this.TextBox1.Size = new System.Drawing.Size(100, 20); this.TextBox1.TabIndex = 2;

Note Setting the Margin property causes a Padding object constructor to display in the

initialization code, both the control's Margin and Padding properties accept this same type to

govern different regions of space to present the control's layout.

Next you return to Design view and select the Button control, to display its properties in the Properties

window.

You want to set the control's Padding properties to ensure that the button text – "Print" – is adequately

spaced in relation to the control's borders.

Before you change the Padding property, however, you need to enable the control to resize its borders

so that the content is not pushed beyond the visible range.

You place your cursor in the AutoSize text box in the Properties window, click the down-pointing arrow that displays, and select True from the drop-down list.

You have now enabled the AutoSize property of the Button control, and can set its Padding

properties.

So you scroll down and expand the Padding node in the Properties window.

To apply a uniform padding measurement – in pixels – to the control, you type 5 in the All text box and

press Enter. The settings in the Left, Top, Right, and Bottom text boxes under the Padding node then update automatically to the same value, and the Button control resizes on the form.

You access the Form5.Designer.cs code to view the updated code in the form's InitializeComponent method. The code now sets the Padding property you've specified for the

Button control.

//

Page 25: 1_Windows Forms Creation With C# 2005

//Button1 // this.Button1.AutoSize = true; this.Button1.Location = new System.Drawing.Point(107, 223); this.Button1.Name = "Button1"; this.Button1.Padding = new System.Windows.Forms.Padding(5); this.Button1.Size = new System.Drawing.Size(75, 33); this.Button1.TabIndex = 1; this.Button1.Text = "&Print"; this.Button1.UseVisualStyleBackColor = true; // //Label1 // this.Label1.AutoSize = true; this.Label1.Location = new System.Drawing.Point(25, 41); this.Label1.Margin = new System.Windows.Forms.Padding(25); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(35, 13); this.Label1.TabIndex = 3; this.Label1.Text = "Name"; // //TextBox1 // this.TextBox1.Location = new System.Drawing.Point(110, 34); this.TextBox1.Margin = new System.Windows.Forms.Padding(25); this.TextBox1.Name = "TextBox1";

Last, you want to set the Dock property of the Button control to align it to the bottom edge of the form.

To do this, you first open the code editor by clicking the Form5.cs tab. You then set the required property value.

public class DialogBox{ private void DialogBox_Load(object sender, System.EventArgs e) { this.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedDialog;

}

private void Button1_Click(object sender, System.EventArgs e) { Button1.MISSING CODE;

}}

Page 26: 1_Windows Forms Creation With C# 2005

You type Dock = DockStyle.Bottom to complete the code.

You have successfully aligned the Button control to the bottom edge of the form. You set the Dock

property in the Click event handler to ensure that it applies at runtime only, when the button is clicked.

public class DialogBox{ private void DialogBox_Load(object sender, System.EventArgs e) { this.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedDialog;

}

private void Button1_Click(object sender, System.EventArgs e) { Button1.Dock = DockStyle.Bottom;

}}

Question

You've added a TextBox control to a form. You now want to set the control's

Margin properties to ensure that the control is kept a certain distance away from

the borders of other controls you add to the form. To do this, you've already selected the text box and opened the Properties window.

How do you set all margins for the control to a value of 10 pixels?

Options:

1. Expand the Margin node in the Properties window, type 10 in the All text box, and

press Enter

2. Expand the Margin entry in the Properties window

3. Expand the Padding node in the Properties window, type 10 in the All text box, and

press Enter

Answer

To set all margins for the TextBox control to a value of 10 pixels, you expand the Margin node in the Properties window, type 10 in the All text box, and press

Enter.

Question

Page 27: 1_Windows Forms Creation With C# 2005

Suppose you have created a Windows form and you want to control the form's behavior by preventing the resizing of the form.

Which property can you use to do this?

Options:

1. Dock

2. FormBorderStyle

3. Margin

4. Padding

Answer

You can use the FormBorderStyle property to control the form's behavior by

preventing the resizing of the form.

Option 1 is incorrect. The Dock property specifies the location of a control on a

form relative to the form's borders.

Option 2 is correct. The FormBorderStyle property enables you to control a

form's resizing behavior by setting a border style for the form. You can set this property to FixedDialog, FixedSingle, or Fixed3D to prevent resizing.

Option 3 is incorrect. The Margin properties of a control set the sizes of its

margins. You can use a control's Margin properties to ensure that other controls

are kept a certain distance away from its borders.

Option 4 is incorrect. The Padding property keeps a control's content a certain

distance away from that control's borders.

3. Setting tab order

When you add controls to a form in Visual Studio 2005, the controls automatically assume a tab order based on the order in which you added the controls. This tab order determines the sequence in which the controls will be selected when a user presses the Tab key to navigate between controls at runtime.

To ensure that the tab order flows smoothly from the top controls to the bottom controls, you can set each control's TabIndex property to specify the order in which it will be selected.

Suppose you want to set the tab order for the Label, TextBox, and Button controls you've added to a

form, so that the controls will be selected in order – from left to right, and from top to bottom.

Page 28: 1_Windows Forms Creation With C# 2005

To set the TabIndex properties of the controls to the appropriate values using code instead of Design

view properties, you first open the InitializeComponent method for the form in the code editor and

scroll down to the code that sets the initial properties of the controls.

// this.Button1.AutoSize = true; this.Button1.Location = new System.Drawing.Point(107, 223); this.Button1.Name = "Button1"; this.Button1.Padding = new System.Windows.Forms.Padding(5); this.Button1.Size = new System.Drawing.Size(75, 33);

this.Button1.Text = "&Print"; this.Button1.UseVisualStyleBackColor = true; // //Label1 // this.Label1.AutoSize = true; this.Label1.Location = new System.Drawing.Point(25, 41); this.Label1.Margin = new System.Windows.Forms.Padding(25); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(35, 13);

this.Label1.Text = "Name"; // //TextBox1 // this.TextBox1.Location = new System.Drawing.Point(110, 34); this.TextBox1.Margin = new System.Windows.Forms.Padding(25); this.TextBox1.Name = "TextBox1"; this.TextBox1.Size = new System.Drawing.Size(100, 20);

Because you've included a Button control – a Print button – at the bottom of your form, you want to set

this button to receive tab focus third – after the Label and TextBox controls that display above it. To do

this, you add a line of code to the properties for the Button control, which is named Button1.

// this.Button1.AutoSize = true; this.Button1.Location = new System.Drawing.Point(107, 223); this.Button1.Name = "Button1"; this.Button1.Padding = new System.Windows.Forms.Padding(5); this.Button1.Size = new System.Drawing.Size(75, 33); this.Button1.MISSING CODE; this.Button1.Text = "&Print"; this.Button1.UseVisualStyleBackColor = true; //

Page 29: 1_Windows Forms Creation With C# 2005

//Label1 // this.Label1.AutoSize = true; this.Label1.Location = new System.Drawing.Point(25, 41); this.Label1.Margin = new System.Windows.Forms.Padding(25); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(35, 13);

this.Label1.Text = "Name"; // //TextBox1 // this.TextBox1.Location = new System.Drawing.Point(110, 34); this.TextBox1.Margin = new System.Windows.Forms.Padding(25); this.TextBox1.Name = "TextBox1"; this.TextBox1.Size = new System.Drawing.Size(100, 20);

You type TabIndex = 3 to complete the code that sets the property.

Once you've set the tab order for the Button control to 3, you want to set the tab order for the Label

control to 1 and the TextBox control to 2.

You type this.Label1.TabIndex = 1; to set the tab order for the Label control.

And you type this.TextBox1.TabIndex = 2; to set the tab order for the TextBox control.

// this.Button1.AutoSize = true; this.Button1.Location = new System.Drawing.Point(107, 223); this.Button1.Name = "Button1"; this.Button1.Padding = new System.Windows.Forms.Padding(5); this.Button1.Size = new System.Drawing.Size(75, 33); this.Button1.TabIndex = 3; this.Button1.Text = "&Print"; this.Button1.UseVisualStyleBackColor = true; // //Label1 // this.Label1.AutoSize = true; this.Label1.Location = new System.Drawing.Point(25, 41); this.Label1.Margin = new System.Windows.Forms.Padding(25); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(35, 13); this.Label1.TabIndex = 1; this.Label1.Text = "Name"; //

Page 30: 1_Windows Forms Creation With C# 2005

//TextBox1 // this.TextBox1.Location = new System.Drawing.Point(110, 34); this.TextBox1.Margin = new System.Windows.Forms.Padding(25); this.TextBox1.Name = "TextBox1"; this.TextBox1.Size = new System.Drawing.Size(100, 20); this.TextBox1.TabIndex = 2;

You've now set the required tab order for three controls on a form.

// this.Button1.AutoSize = true; this.Button1.Location = new System.Drawing.Point(107, 223); this.Button1.Name = "Button1"; this.Button1.Padding = new System.Windows.Forms.Padding(5); this.Button1.Size = new System.Drawing.Size(75, 33); this.Button1.TabIndex = 3; this.Button1.Text = "&Print"; this.Button1.UseVisualStyleBackColor = true; // //Label1 // this.Label1.AutoSize = true; this.Label1.Location = new System.Drawing.Point(25, 41); this.Label1.Margin = new System.Windows.Forms.Padding(25); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(35, 13); this.Label1.TabIndex = 1; this.Label1.Text = "Name"; // //TextBox1 // this.TextBox1.Location = new System.Drawing.Point(110, 34); this.TextBox1.Margin = new System.Windows.Forms.Padding(25); this.TextBox1.Name = "TextBox1"; this.TextBox1.Size = new System.Drawing.Size(100, 20); this.TextBox1.TabIndex = 2;

Question

Suppose you want to set the tab order for a Button control on your form, to

ensure that it's the fifth control that will be selected when a user tabs between controls at runtime.

Complete the code to do this.

Page 31: 1_Windows Forms Creation With C# 2005

this.Button1.AutoSize = true; this.Button1.Location = new System.Drawing.Point(107, 223); this.Button1.Name = "Button1"; this.Button1.Padding = new System.Windows.Forms.Padding(5); this.Button1.Size = new System.Drawing.Size(75, 33); this.MISSING CODE; this.Button1.Text = "&Print"; this.Button1.UseVisualStyleBackColor = true;

Answer

To set the tab order for a Button control on a form to 5, you type

Button1.TabIndex = 5

4. Setting accessibility properties

Visual Studio 2005 enables you to set accessibility properties for controls, to ensure that people with disabilities can still use applications you design.

For example, you can use accessibility properties to provide descriptions of controls or their values to visually impaired users who rely on screen readers and to users who use voice input instead of a mouse or keyboard to interact with an application.

The following accessibility properties display in the Properties window for all controls:

AccessibleDescription

AccessibleName

AccessibleRole

AccessibleDescription

The AccessibleDescription property provides a description of a particular control.

For example, you may use this property to describe a control as a "Print button."

AccessibleName

The AccessibleName property identifies the text used to name the control onscreen.

AccessibleRole

The AccessibleRole property sets the role of a particular control that will be reported to

accessibility users. For example, it may identify the role of a control as "PushButton," to

specify that it is a button that can be clicked.

Page 32: 1_Windows Forms Creation With C# 2005

Once you've set the AccessibleDescription, AccessibleName, and AccessibleRole properties

using the Properties window, code in the Form Designer updates with the settings automatically.

// //Button1 // this.Button1.AccessibleDescription = "Print button"; this.Button1.AccessibleName = "Print"; this.Button1.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.Button1.AutoSize = true; this.Button1.Location = new System.Drawing.Point(107, 223); this.Button1.Name = "Button1"; this.Button1.Padding = new System.Windows.Forms.Padding(5); this.Button1.Size = new System.Drawing.Size(75, 33); this.Button1.TabIndex = 5; this.Button1.Text = "&Print"; this.Button1.UseVisualStyleBackColor = true; // //Label1 // this.Label1.AutoSize = true; this.Label1.Location = new System.Drawing.Point(25, 41); this.Label1.Margin = new System.Windows.Forms.Padding(25); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(35, 13); this.Label1.TabIndex = 0; this.Label1.Text = "Name"; // //TextBox1

In addition to the accessibility properties in the Properties window, Visual Studio 2005 supports the AccessibilityObject and AccessibleDefaultActionDescription control properties.

The AccessibilityObject property informs the user about a control's position on screen, its value

and description, and its navigational uses. The AccessibilityObject property is automatically set

when you add a control to a form.

The AccessibleDefaultActionDescription property informs the user of the default action that a

specific control performs. This property may only be set in code.

// //Button1 // this.Button1.AccessibleDescription = "Print button";

Page 33: 1_Windows Forms Creation With C# 2005

this.Button1.AccessibleName = "Print"; this.Button1.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.Button1.AutoSize = true; this.Button1.Location = new System.Drawing.Point(107, 223); this.Button1.Name = "Button1"; this.Button1.Padding = new System.Windows.Forms.Padding(5); this.Button1.Size = new System.Drawing.Size(75, 33); this.Button1.TabIndex = 5; this.Button1.Text = "&Print"; this.Button1.UseVisualStyleBackColor = true; // //Label1 // this.Label1.AutoSize = true; this.Label1.Location = new System.Drawing.Point(25, 41); this.Label1.Margin = new System.Windows.Forms.Padding(25); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(35, 13); this.Label1.TabIndex = 0; this.Label1.Text = "Name"; // //TextBox1

In the initialization code for a Button control, suppose you want to set an accessibility property for the

control.

// //Button1 // this.Button1.AccessibleMISSING CODE = "Closes the application"; this.Button1.AccessibleDescription = "Print button"; this.Button1.AccessibleName = "Print"; this.Button1.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.Button1.AutoSize = true; this.Button1.Location = new System.Drawing.Point(107, 223); this.Button1.Name = "Button1"; this.Button1.Padding = new System.Windows.Forms.Padding(5); this.Button1.Size = new System.Drawing.Size(75, 33); this.Button1.TabIndex = 5; this.Button1.Text = "&Print"; this.Button1.UseVisualStyleBackColor = true; // //Label1

Page 34: 1_Windows Forms Creation With C# 2005

// this.Label1.AutoSize = true; this.Label1.Location = new System.Drawing.Point(25, 41); this.Label1.Margin = new System.Windows.Forms.Padding(25); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(35, 13); this.Label1.TabIndex = 0; this.Label1.Text = "Name";

You type DefaultActionDescription.

You have set an accessibility property for your Button control – AccessibleDefaultActionDescription.

// //Button1 // this.Button1.AccessibleDefaultActionDescription = "Closes the application"; this.Button1.AccessibleDescription = "Print button"; this.Button1.AccessibleName = "Print"; this.Button1.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.Button1.AutoSize = true; this.Button1.Location = new System.Drawing.Point(107, 223); this.Button1.Name = "Button1"; this.Button1.Padding = new System.Windows.Forms.Padding(5); this.Button1.Size = new System.Drawing.Size(75, 33); this.Button1.TabIndex = 5; this.Button1.Text = "&Print"; this.Button1.UseVisualStyleBackColor = true; // //Label1 // this.Label1.AutoSize = true; this.Label1.Location = new System.Drawing.Point(25, 41); this.Label1.Margin = new System.Windows.Forms.Padding(25); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(35, 13); this.Label1.TabIndex = 0; this.Label1.Text = "Name";

Question

Suppose you want to set an accessibility property to inform an accessibility user of the default value for your Button control – to open your form.

Page 35: 1_Windows Forms Creation With C# 2005

Complete the code to do this.

// //Button1 // this.Button1.AccessibleMISSING CODE = "Opens your form"; this.Button1.AccessibleDescription = "Print button"; this.Button1.AccessibleName = "Print"; this.Button1.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.Button1.AutoSize = true; this.Button1.Location = new System.Drawing.Point(107, 223); this.Button1.Name = "Button1"; this.Button1.Padding = new System.Windows.Forms.Padding(5); this.Button1.Size = new System.Drawing.Size(75, 33); this.Button1.TabIndex = 5; this.Button1.Text = "&Print"; this.Button1.UseVisualStyleBackColor = true; // //Label1 // this.Label1.AutoSize = true; this.Label1.Location = new System.Drawing.Point(25, 41); this.Label1.Margin = new System.Windows.Forms.Padding(25); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(35, 13); this.Label1.TabIndex = 0; this.Label1.Text = "Name";

Answer

To set an accessibility property for the Button control, you type

DefaultActionDescription

Question

Suppose you're creating accessibility features for a form and you want to include a description of the role of the OK button for accessibility users.

Which line of code do you use to do this?

Page 36: 1_Windows Forms Creation With C# 2005

Options:

1. this.Button1.AccessibleDescription = "OK button";

2. this.Button1.AccessibleName = "OK";

3. this.Button1.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton;

Answer

To set the role of the OK button for accessibility users, you use the code

this.Button1.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton;

Option 1 is incorrect. This code provides a description of the control's use, rather than of its role – or type.

Option 2 is incorrect. This code identifies only the name of the control, as it displays onscreen.

Option 3 is correct. This code sets the role of the OK button as "PushButton," to describe its role to accessibility users.

5. Setting form behavior

Once you have designed a form and configured its layout and appearance, you can set properties to control the way the form behaves.

These properties are usually configured in the Form Designer. All changes you make to the Form Designer – the InitializeComponent code for the form – are shown in the form automatically.

Examples of form properties you can use to control form behavior are

AlwaysOnTop

Closable

Movable

TitleBar

WindowState

AlwaysOnTop

The AlwaysOnTop property determines whether a form should be placed over other

forms. By default, this property is set to False.

Closable

Page 37: 1_Windows Forms Creation With C# 2005

The Closable property determines the way in which users are able to close the form – for

example by clicking the Close button. By default, this property is set to True.

Movable

The Movable property determines whether a user is able to move the form around on

screen. By default, this property is set to True.

TitleBar

The TitleBar property determines whether a title bar displays on the form. By default,

this property is set to On.

WindowState

The WindowState property determines the size of the form – minimized, maximized, or

normal – when it is opened. By default, this property is set to Normal.

In addition to the AlwaysOnTop, BorderStyle, Closable, Movable, TitleBar, and

WindowState properties, Visual Studio 2005 includes various other properties for

controlling form behavior.

Other properties for controlling form behavior in Visual Studio 2005

In addition to the AlwaysOnTop, BorderStyle, Closable, Movable, TitleBar, and WindowState

properties, Visual Studio 2005 includes the following properties for controlling form behavior:

Other properties for controlling form behavior.

Class Description

AutoCenter Automatically centers the form when the application is run

BackColor Specifies the background color of the form

Caption Specifies the text that is displayed in the form's title bar

DataSession Determines whether the form's tables are opened in globally accessible or private work areas

MaxButton Specifies the inclusion of a Maximize button for the form

MinButton Specifies the inclusion of a Minimize button for the form

ScaleMode Specifies the form's unit of measurement

Page 38: 1_Windows Forms Creation With C# 2005

Class Description

ScrollBars Determines the type of scroll bar used on the form

ShowWindow Determines where the form is displayed on screen – it can be floating or at the top level

WindowType Determines whether the form is modal or modeless

View a list of other properties for controlling form behavior (above)

Suppose you want to set a form to a specific state – maximized – when it is opened in Visual Studio 2005.

You click the WindowState down-pointing arrow, and select Maximized from the drop-down list.

Your form will now be maximized when a user runs the application.

Summary

Visual Studio 2005 enables you to configure several properties of forms and the controls they include to control form appearance, accessibility, and behavior. To configure an access key that provides a shortcut for a common control, you add an ampersand character (&) in front of the character that must act as the

key, in the control's Text property.

You can configure a form's layout and appearance using its FormBorderStyle property, and the

Margin, Padding, and Dock properties of individual controls. To set the values of these properties, you

can use the Properties window in Design view or add to form code in the Form Designer window.

You can set a specific tab order for the controls on a form using each control's TabIndex property.

Accessibility properties you can set in Visual Studio 2005 include AccessibleDescription,

AccessibleName, AccessibleRole, AccessibleDefaultActionDescription, and

AccessibilityObject.

After you've configured the appearance and accessibility of a form, you can use properties to control its runtime behavior. Examples of these properties are AlwaysOnTop, BorderStyle, Closable,

Movable, TitleBar, and WindowState.

Display Controls and Containers in Windows Forms

Page 39: 1_Windows Forms Creation With C# 2005

Learning objective

After completing this topic, you should be able to identify how to create display controls and dynamic container areas in Windows forms.

1. Adding Panel and GroupBox controls

You can use various types of controls in Visual Studio 2005 to arrange and group content on a form. These controls are known as display and container controls.

Common types of container controls in C# 2005 are the

Panel control

GroupBox control

TabControl control

FlowLayoutPanel control

TableLayoutPanel control

SplitContainer control

Panel control

The Panel control is a large container that holds other controls and has no caption. You

use the Panel control to group collections of other controls, such as radio buttons. If you

choose to disable the Panel control, all controls within the panel are also disabled.

GroupBox control

The GroupBox control provides a logical grouping of other controls with a frame and

caption. For example, it ensures that only one radio button within its borders can be

selected at a time.

TabControl control

The TabControl control contains multiple TabPage objects. You can add various

controls to these pages and view each page by clicking the appropriate tab on the control.

FlowLayoutPanel control

The FlowLayoutPanel control looks similar to a Panel control, but sets its contents out

either vertically or horizontally on a form.

TableLayoutPanel control

The TableLayoutPanel control organizes controls in rows and columns within a grid-like

structure. All controls inside this type of panel will automatically resize if their contents

change.

SplitContainer control

Page 40: 1_Windows Forms Creation With C# 2005

The SplitContainer control has two resizable panels, separated by an adjustable bar

called a splitter. You can use this control to separate a form's display area, and users can

resize the panels it provides at runtime.

By default, the Panel control has no borders, but you can set borders using its

BorderStyle property. For example, you can create a single border style using the

FixedSingle property. You can also add scrollbars to a Panel control using its

AutoScroll property.

To add and configure a Panel control at runtime, you should

create a new subroutine and initialize a new Panel control

set relevant properties such as BorderStyle

create any relevant controls for the Panel

add the Panel control to the form

use the Add method to add the controls to the Panel container

Suppose you want to create a Panel control and add Label and TextBox controls to the container. You

also want to add a fixed single-line border to the Panel control.

public class Form2{}

First you create a new subroutine, CreateMyPanel, and initialize a Panel control named Panel1. You

set the location of the control – relative to the top left corner of the form – to the coordinates 14, 11 and

set its size as 200 by 100.

public class Form2{

public void CreateMyPanel() { Panel Panel1 = new Panel();

Panel1.Location = new Point(14, 11); Panel1.Size = new Size(200, 100); }

}

Then you set the Panel control's BorderStyle property to FixedSingle to create a single-line border

style.

Page 41: 1_Windows Forms Creation With C# 2005

public class Form2{

public void CreateMyPanel() { Panel Panel1 = new Panel();

Panel1.Location = new Point(14, 11); Panel1.Size = new Size(200, 100); Panel1.BorderStyle = System.Windows.Forms.MISSING CODE; }

}

You type BorderStyle.FixedSingle to complete the code that does this.

You have set a single-line border style for the Panel control.

public class Form2{

public void CreateMyPanel() { Panel Panel1 = new Panel();

Panel1.Location = new Point(14, 11); Panel1.Size = new Size(200, 100); Panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; }

}

Next you initialize the Label and TextBox controls by setting their Location, Text, and Size

properties, in the subroutine that creates and configures the Panel control.

public class Form2{

public void CreateMyPanel() { Panel Panel1 = new Panel(); TextBox TextBox1 = new TextBox(); Label Label1 = new Label();

Page 42: 1_Windows Forms Creation With C# 2005

Panel1.Location = new Point(14, 11); Panel1.Size = new Size(200, 100); Panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

Label1.Location = new Point(14, 19); Label1.Text = "Label1"; Label1.Size = new Size(39, 13); TextBox1.Location = new Point(69, 19); TextBox1.Text = ""; TextBox1.Size = new Size(100, 20); }

}

You use the Add method to add the Panel control to the form. This method is a member of the

ControlCollection class, for which an object resides in the form's Controls property.

public class Form2{

public void CreateMyPanel() { Panel Panel1 = new Panel(); TextBox TextBox1 = new TextBox(); Label Label1 = new Label();

Panel1.Location = new Point(14, 11); Panel1.Size = new Size(200, 100); Panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

Label1.Location = new Point(14, 19); Label1.Text = "Label1"; Label1.Size = new Size(39, 13); TextBox1.Location = new Point(69, 19); TextBox1.Text = ""; TextBox1.Size = new Size(100, 20);

this.Controls.MISSING CODE; }}

You type Add(Panel1) to complete the code that adds the control.

Page 43: 1_Windows Forms Creation With C# 2005

You have added the Panel control to the form.

public class Form2{

public void CreateMyPanel() { Panel Panel1 = new Panel(); TextBox TextBox1 = new TextBox(); Label Label1 = new Label();

Panel1.Location = new Point(14, 11); Panel1.Size = new Size(200, 100); Panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

Label1.Location = new Point(14, 19); Label1.Text = "Label1"; Label1.Size = new Size(39, 13); TextBox1.Location = new Point(69, 19); TextBox1.Text = ""; TextBox1.Size = new Size(100, 20);

this.Controls.Add(Panel1);

Finally, you use the Add method to add the Label and TextBox controls to the Panel control's own

Controls collection. Upon adding, the Location property for these controls is now relative to the upper

left corner of the Panel and not that of the form.

Panel1.Controls.Add(Label1); Panel1.Controls.Add(TextBox1); }

}

At runtime, the Panel control you've created displays on the form with a fixed single border, and contains

Label and TextBox controls.

A GroupBox control has a caption – by default, GroupBox1 – and a single-line border. You can use its

FlatStyle property to alter its appearance, which takes a value of the enumeration of the same name.

For example, you could create a 3-D look using the Popup enumeration value.

You cannot add scroll bars to a GroupBox control.

Page 44: 1_Windows Forms Creation With C# 2005

To add and configure a GroupBox control at runtime, you should

create a new subroutine and initialize a GroupBox and any relevant controls

set all relevant properties

add the necessary controls to the GroupBox container

add the GroupBox container to the form

Suppose you want to create a GroupBox control and then add a RadioButton control to it.

In a subroutine, you first initialize a GroupBox control and a RadioButton control.

private void InitializeMyGroupBox() { GroupBox GroupBox1 = new GroupBox(); RadioButton RadioButton1 = new RadioButton();

You then use the Location property of the RadioButton control to specify where it will appear relative

to the upper left-hand corner of any container it will be placed within.

RadioButton1.Location = new Point(19, 29); }

Then you set the GroupBox control on the form that contains a RadioButton control. If you wish to

change the GroupBox's caption from GroupBox1, you can set the Text property in the subroutine you

created.

private void InitializeMyGroupBox() { GroupBox GroupBox1 = new GroupBox(); RadioButton RadioButton1 = new RadioButton(); RadioButton1.Location = new Point(19, 29); RadioButton1.Text = "RadioButton1"; GroupBox1.FlatStyle = MISSING CODE; }

You type FlatStyle.Popup to complete the code.

You have specified the use of the Popup style for the GroupBox control.

private void InitializeMyGroupBox() {

Page 45: 1_Windows Forms Creation With C# 2005

GroupBox GroupBox1 = new GroupBox(); RadioButton RadioButton1 = new RadioButton(); RadioButton1.Location = new Point(19, 29); RadioButton1.Text = "RadioButton1"; GroupBox1.FlatStyle = FlatStyle.Popup; }

Finally, you add the RadioButton control to the GroupBox container. It will appear in the container at a

location specified by the Location property.

private void InitializeMyGroupBox() { GroupBox GroupBox1 = new GroupBox(); RadioButton RadioButton1 = new RadioButton(); RadioButton1.Location = new Point(19, 29); RadioButton1.Text = "RadioButton1"; GroupBox1.FlatStyle = FlatStyle.Popup; GroupBox1.Text = "GroupBox1"; GroupBox1.Controls.Add(RadioButton1);}

And you add the GroupBox container to the form.

Controls.Add(GroupBox1); }

You have created a GroupBox control that contains a RadioButton control to the form.

Question

Suppose you want to configure a Panel control to include a single-line border.

Complete the code to do this.

public class Form2{

public void DisplayPanel() { Panel DispPanel1 = new Panel(); DispPanel1.Location = new Point(22, 9); DispPanel1.Size = new Size(110, 250); DispPanel1.BorderStyle = System.Windows.Forms.MISSING

Page 46: 1_Windows Forms Creation With C# 2005

CODE;

}

}

Answer

To complete the code that adds a fixed single-line border to the Panel control,

you type

BorderStyle.FixedSingle

Question

Suppose you want to create a form with ten Label controls. These controls must

remain visible at all times and be grouped logically. These controls are named after their type.

Which line of code should you use to add an appropriate control to the form that can group the Label controls?

Options:

1. this.Controls.Add(Panel1)

2. this.TabControl1.Controls.Add(this.TabPage1)

3. Panel1.Controls.Add(Label1)

Answer

To ensure the collection of RadioButton controls will be grouped together on the

form, you use the code

this.Controls.Add(Panel1)

Option 1 is correct. This code adds a Panel control to a form. This control is used

to group collections of controls on a form.

Option 2 is incorrect. This code adds a tabbed page to a TabControl control.

Controls can be grouped on a tabbed page, but if other tabbed pages are selected, the controls may not be seen.

Option 3 is incorrect. This code adds a Label control to the Panel rather than

adding the required Panel container control to the form.

Page 47: 1_Windows Forms Creation With C# 2005

2. Adding a TabControl control

To configure a TabControl control programmatically, you can

create tabbed pages, as objects of the TabPage class

add the pages to the TabControl control

add the TabControl to a form using the Add method of the ControlCollection class

You can use the ForeColor property of the TabPage control to adjust the appearance of the client area

of the tabbed pages it contains. By default, this property is set to the value of the static ControlText

property of the SystemColors class.

Suppose you want to add a TabControl container with two tabbed pages to a form. To the first tabbed

page, you want to add a Button control.

You first create and declare the TabPage objects – or tabbed pages – you want to add to the control.

public class Form1{ public void MyOwnSub() { TabPage MyTPage1 = new TabPage(); TabPage MyTPage2 = new TabPage(); TabControl MyTControl = new TabControl(); Button FirstButton = new Button();

Then you add and configure the properties for the tabbed pages. For example, you set the Text property of a TabPage object to specify what text must display on its tab.

MyTPage1.Name = "TabPage1"; MyTPage1.Padding = new Padding(3); MyTPage1.Size = new Size(211, 91); MyTPage1.Text = "TabPage1";

//Set MyTPage2 properties here }}

To add a Button control to the first tabbed page, you use a method of the Controls class.

public class Form1{

Page 48: 1_Windows Forms Creation With C# 2005

public void MyOwnSub() { TabPage MyTPage1 = new TabPage(); TabPage MyTPage2 = new TabPage(); TabControl MyTControl = new TabControl(); Button FirstButton = new Button();

MyTPage1.Name = "TabPage1"; MyTPage1.Padding = new Padding(3); MyTPage1.Size = new Size(211, 91); MyTPage1.Text = "TabPage1";

//Set MyTPage2 properties here

FirstButton.Text = "Button1"; MyTPage1.Controls.Add MISSING CODE; }}

You type (FirstButton) to complete the code.

You have added a Button control to the first tabbed page.

public class Form1{ public void MyOwnSub() { TabPage MyTPage1 = new TabPage(); TabPage MyTPage2 = new TabPage(); TabControl MyTControl = new TabControl(); Button FirstButton = new Button();

MyTPage1.Name = "TabPage1"; MyTPage1.Padding = new Padding(3); MyTPage1.Size = new Size(211, 91); MyTPage1.Text = "TabPage1";

//Set MyTPage2 properties here

FirstButton.Text = "Button1"; MyTPage1.Controls.Add(FirstButton); }}

Next you add the first tabbed page – named MyTPage1 – to the TabControl control.

Page 49: 1_Windows Forms Creation With C# 2005

public class Form1{ public void MyOwnSub() { TabPage MyTPage1 = new TabPage(); TabPage MyTPage2 = new TabPage(); TabControl MyTControl = new TabControl(); Button FirstButton = new Button();

MyTPage1.Name = "TabPage1"; MyTPage1.Padding = new Padding(3); MyTPage1.Size = new Size(211, 91); MyTPage1.Text = "TabPage1";

//Set MyTPage2 properties here

FirstButton.Text = "Button1"; MyTPage1.Controls.Add(FirstButton); MyTControl.Controls.MISSING CODE; }}

You type Add(MyTPage1) to complete the code.

You have added the first tabbed page to the control.

public class Form1{ public void MyOwnSub() { TabPage MyTPage1 = new TabPage(); TabPage MyTPage2 = new TabPage(); TabControl MyTControl = new TabControl(); Button FirstButton = new Button();

MyTPage1.Name = "TabPage1"; MyTPage1.Padding = new Padding(3); MyTPage1.Size = new Size(211, 91); MyTPage1.Text = "TabPage1";

//Set MyTPage2 properties here

FirstButton.Text = "Button1"; MyTPage1.Controls.Add(FirstButton); MyTControl.Controls.Add(MyTPage1);

Page 50: 1_Windows Forms Creation With C# 2005

You add the second tabbed page in the same way.

MyTControl.Controls.Add(MyTPage2); }}

Next you configure the TabControl control.

public class Form1{ public void MyOwnSub() { TabPage MyTPage1 = new TabPage(); TabPage MyTPage2 = new TabPage(); TabControl MyTControl = new TabControl(); Button FirstButton = new Button();

MyTPage1.Name = "TabPage1"; MyTPage1.Padding = new Padding(3); MyTPage1.Size = new Size(211, 91); MyTPage1.Text = "TabPage1";

//Set MyTPage2 properties here

FirstButton.Text = "Button1"; MyTPage1.Controls.Add(FirstButton); MyTControl.Controls.Add(MyTPage1); MyTControl.Controls.Add(MyTPage2);

MyTControl.Location = new Point(12, 12); MyTControl.Size = new Size(219, 117); MyTControl.TabIndex = 0; }}

Finally, you add the TabControl control to the form.

public class Form1{ public void MyOwnSub() { TabPage MyTPage1 = new TabPage(); TabPage MyTPage2 = new TabPage(); TabControl MyTControl = new TabControl(); Button FirstButton = new Button();

Page 51: 1_Windows Forms Creation With C# 2005

MyTPage1.Name = "TabPage1"; MyTPage1.Padding = new Padding(3); MyTPage1.Size = new Size(211, 91); MyTPage1.Text = "TabPage1";

//Set MyTPage2 properties here

FirstButton.Text = "Button1"; MyTPage1.Controls.Add(FirstButton); MyTControl.Controls.Add(MyTPage1); MyTControl.Controls.Add(MyTPage2);

MyTControl.Location = new Point(12, 12); MyTControl.Size = new Size(219, 117); MyTControl.TabIndex = 0; MISSING CODE(MyTControl); }}

You type this.Controls.Add to complete the code.

You have added the TabControl control to the form. The subroutine can then be run from the

Form_Load event.

public class Form1{ public void MyOwnSub() { TabPage MyTPage1 = new TabPage(); TabPage MyTPage2 = new TabPage(); TabControl MyTControl = new TabControl(); Button FirstButton = new Button();

MyTPage1.Name = "TabPage1"; MyTPage1.Padding = new Padding(3); MyTPage1.Size = new Size(211, 91); MyTPage1.Text = "TabPage1";

//Set MyTPage2 properties here

FirstButton.Text = "Button1"; MyTPage1.Controls.Add(FirstButton); MyTControl.Controls.Add(MyTPage1); MyTControl.Controls.Add(MyTPage2);

Page 52: 1_Windows Forms Creation With C# 2005

MyTControl.Location = new Point(12, 12); MyTControl.Size = new Size(219, 117); MyTControl.TabIndex = 0; this.Controls.Add(MyTControl); }}

In Design view, a TabControl control that includes two tabbed pages now displays on the form. The first

tabbed page includes a Button control.

Question

Suppose you want to add a TabControl control – named TabControl1 – to a

Windows form.

Complete the code to do this.

public class MyOwnForm{

//...

public void TabC() {

TabPage PageTb = new TabPage(); TabControl TabControl1 = new TabControl();

TabControl1.Controls.Add(PageTb);

this.Controls.MISSING CODE; }}

Answer

To complete the code that adds TabControl1 control to a Windows form, you

type

Add(TabControl1)

3. Adding LayoutPanel controls

Page 53: 1_Windows Forms Creation With C# 2005

You can specify the flow direction for a FlowLayoutPanel control by setting its FlowDirection

property to LeftToRight, TopDown, RightToLeft, or BottomUp.

You can also choose whether to wrap the contents of the FlowLayoutPanel control by setting the

WrapContents property to either True or False.

Suppose you've added a FlowLayoutPanel control to a form and configured its properties using Design

view in Visual Studio 2005.

using System;using System.Windows.Forms;

public class Form5 : System.Windows.Forms.Form{

}

You have added a checkbox named CB1 to the FlowControlPanel control through the designer to

indicate whether the contents will wrap at the control boundary. So you create an event handler for the CheckBox control's CheckedChanged event, which occurs when the checkbox is selected by a user at

runtime.

using System;using System.Windows.Forms;

public class Form5 : System.Windows.Forms.Form{ private void CB1_CheckedChanged(object sender, System.EventArgs e) {

}}

Now you want to set the WrapContents property for the FlowLayoutPanel container. If the CheckBox

control is selected, the control's contents will be wrapped at the control boundary. If the CheckBox control

is not selected, no wrapping will occur.

using System;using System.Windows.Forms;

public class Form5 : System.Windows.Forms.Form{

Page 54: 1_Windows Forms Creation With C# 2005

private void CB1_CheckedChanged(object sender, System.EventArgs e) {

this.FlowLayoutPanel1.MISSING CODE = this.CB1.Checked; }}

You type WrapContents.

You have set the WrapContents property for the FlowLayoutPanel container. If the CheckBox

control is selected, the control's contents will be wrapped at the control boundary. If not, the controls will continue off the boundary containing the LayoutPanel control, and become invisible.

using System;using System.Windows.Forms;

public class Form5 : System.Windows.Forms.Form{ private void CB1_CheckedChanged(object sender, System.EventArgs e) {

this.FlowLayoutPanel1.WrapContents = this.CB1.Checked; }}

Next suppose you've used Design view to add four RadioButton controls to the FlowLayoutPanel

container – btnTD, btnBU, btnLR, and btnRL. These radio buttons must enable the user to set the

orientation of the control at runtime.

using System;using System.Windows.Forms;

public class Form5 : System.Windows.Forms.Form{ private void CB1_CheckedChanged(object sender, System.EventArgs e) {

this.FlowLayoutPanel1.WrapContents = this.CB1.Checked; }

You then create event handlers for the radio buttons. When the application is run and the TD radio button is selected, for example, the code included in its event handler will execute.

Page 55: 1_Windows Forms Creation With C# 2005

private void btnTD_CheckedChanged(object sender, System.EventArgs e) {

}

}

Now you want to set the FlowDirection property for the first RadioButton control to TopDown. This

will ensure that when the application runs, the top radio button will receive first tab focus and the controls will be ordered top to bottom on the panel.

using System;using System.Windows.Forms;

public class Form5 : System.Windows.Forms.Form{ private void CB1_CheckedChanged(object sender, System.EventArgs e) {

this.FlowLayoutPanel1.WrapContents = this.CB1.Checked; }

private void btnTD_CheckedChanged(object sender, System.EventArgs e) {

this.FlowLayoutPanel1.FlowDirection = MISSING CODE; }}

You type FlowDirection.TopDown to complete the code.

You have set the FlowDirection property for the first RadioButton control to TopDown.

using System;using System.Windows.Forms;

public class Form5 : System.Windows.Forms.Form{ private void CB1_CheckedChanged(object sender, System.EventArgs e) {

Page 56: 1_Windows Forms Creation With C# 2005

this.FlowLayoutPanel1.WrapContents = this.CB1.Checked; }

private void btnTD_CheckedChanged(object sender, System.EventArgs e) {

this.FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown; }}

Next you create an event handler for the second radio button's CheckedChanged event and set the

FlowDirection property for the second RadioButton control to BottomUp.

private void btnTD_CheckedChanged(object sender, System.EventArgs e) {

this.FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown; }

private void btnBU_CheckedChanged(object sender, System.EventArgs e) {

this.FlowLayoutPanel1.FlowDirection = FlowDirection.BottomUp; }}

You add similar code for the third and fourth radio buttons, setting the FlowDirection properties to

LeftToRight and RightToLeft respectively.

private void btnLR_CheckedChanged(object sender, System.EventArgs e){ this.FlowLayoutPanel1.FlowDirection = FlowDirection.LeftToRight;}private void btnRL_CheckedChanged(object sender, System.EventArgs e){ this.FlowLayoutPanel1.FlowDirection = FlowDirection.RightToLeft;

Page 57: 1_Windows Forms Creation With C# 2005

}}

You have added a CheckBox control and four RadioButton controls to a FlowLayoutPanel control,

and set the WrapContents property for the checkbox and the FlowDirection property for each radio

button.

Question

Suppose you have created a FlowLayoutPanel container and added several

RadioButton controls. Now you want to ensure that when the application is run,

the bottom radio button will receive first tab focus.

Complete the code to do this.

private void btnB1_CheckedChanged(object sender, System.EventArgs e){

this.FlowLayoutPanel1.FlowDirection = MISSING CODE;}

Answer

To set the FlowDirection property for the RadioButton control to BottomUp,

you complete the code by typing

FlowDirection.BottomUp

To configure the TableLayoutPanel control, you can use its

ColumnCount, GrowStyle, and RowCount properties to enable the panel to adjust to the

addition of new controls

ColumnStyles and RowStyles properties, to set the characteristics of specific rows or columns

ColumnSpan and RowSpan properties, to merge rows and columns

Margin and Padding properties, to ensure a certain distance is kept between the panel's borders

and other controls

Suppose you want to add a number of controls to a TableLayoutPanel named TlPanel1, and then

upon an event from another control, change the layout of the controls. First you create the class for your form.

Page 58: 1_Windows Forms Creation With C# 2005

In the designer, you add a TableLayoutPanel and a CheckBox control to change its layout. You then

add a handler for the checkbox that will change the layout of the TableLayoutPanel.

public class MyOwnForm : System.Windows.Forms{

private void CheckBox2_CheckedChanged(object sender, System.EventArgs e) {

}}

In Design view, you place a label in each cell. In the event handler, you then create two more labels and add them to the TableLayoutPanel. You explicitly set the panel's ColumnCount to 3.

public class MyOwnForm : System.Windows.Forms{

private void CheckBox2_CheckedChanged(object sender, System.EventArgs e) { Label Label5 = new Label(); Label Label6 = new Label(); Label5.Text = "Label5"; Label6.Text = "Label6";

MISSING CODE = 3; TLPanel1.Controls.Add(Label5); TLPanel1.Controls.Add(Label6); }}

You type TLPanel1.ColumnCount to complete the code.

You have set the number of the TableLayoutPanel's columns to three. This will be done automatically

if the panel's GrowStyle property is set to the AddColumns value of the

TableLayoutPanelGrowStyle enumeration.

public class MyOwnForm : System.Windows.Forms{

//TODO: INSTANT C# TODO TASK: Insert the following converted event

Page 59: 1_Windows Forms Creation With C# 2005

handlers at the end of the 'InitializeComponent' method for forms or into a constructor for other classes:CheckBox2.CheckedChanged += new System.EventHandler(CheckBox2_CheckedChanged);

private void CheckBox2_CheckedChanged(object sender, System.EventArgs e) { Label Label5 = new Label(); Label Label6 = new Label(); Label5.Text = "Label5"; Label6.Text = "Label6";

TLPanel1.ColumnCount = 3; TLPanel1.Controls.Add(Label5); TLPanel1.Controls.Add(Label6); }}

To specify where the controls within the panel must appear in their cells, you set their Anchor properties.

For example, you set the Anchor property of Label1 to AnchorStyles.Right.

public class MyOwnForm : System.Windows.Forms{ private void CheckBox2_CheckedChanged(object sender, System.EventArgs e) { Label Label5 = new Label(); Label Label6 = new Label(); Label5.Text = "Label5"; Label6.Text = "Label6";

TLPanel1.ColumnCount = 3; TLPanel1.Controls.Add(Label5); TLPanel1.Controls.Add(Label6); Label1.Anchor = AnchorStyles.Right; }}

Finally, you change the layout of the columns relative to one another, by setting the RowStyles and

ColumnStyles properties to AutoSize.

TableLayoutColumnStyleCollection Sts = TLPanel1.ColumnStyles; TableLayoutRowStyleCollection Rws = TLPanel1.RowStyles;

Page 60: 1_Windows Forms Creation With C# 2005

foreach (ColumnStyle mySt in Sts) { if (mySt.SizeType == SizeType.Absolute | mySt.SizeType == SizeType.Percent) { mySt.SizeType = SizeType.AutoSize; } }

foreach (RowStyle myRw in Rws) { if (myRw.SizeType == SizeType.Absolute | myRw.SizeType == SizeType.Percent) { myRw.SizeType = SizeType.AutoSize; } }

You have created a custom appearance for a cell in the TableLayoutPanel container.

Question

Suppose you have created a TableLayoutPanel control and you want to merge

rows and columns in the control.

Which properties do you use to do this?

Options:

1. ColumnCount and RowCount

2. ColumnSpan and RowSpan

3. ColumnStyles and RowStyles

4. Margin and Padding

Answer

The ColumnSpan and RowSpan properties enable you to merge rows and

columns in the TableLayoutPanel control.

Option 1 is incorrect. The ColumnCount and RowCount properties are used to

enable the TableLayoutPanel to adjust to the addition of new controls.

Option 2 is correct. The ColumnSpan and RowSpan properties merge the rows

and columns in a TableLayoutPanel control.

Page 61: 1_Windows Forms Creation With C# 2005

Option 3 is incorrect. The ColumnStyles and RowStyles properties help to set

the characteristics of specific rows and columns rather than to merge them.

Option 4 is incorrect. The Margin and Padding properties ensure that a certain

distance is kept between the TableLayoutPanel control's borders and other

controls.

4. Adding a SplitContainer control

To configure a SplitContainer control, you can use properties such as

FixedPanel

SplitterDistance

SplitterIncrement

Panel1MinSize and Panel2MinSize

Orientation

IsSplitterFixed

FixedPanel

You use the FixedPanel property to specify one of the control's panels to remain fixed

when the SplitContainer is resized.

SplitterDistance

You use the SplitterDistance property to specify the location of the splitter that

divides the panels in the SplitContainer control.

SplitterIncrement

You use the SplitterIncrement property to specify the number of pixels by which the

user can move the splitter at once.

Panel1MinSize and Panel2MinSize

You use the Panel1MinSize and Panel2MinSize properties to specify the minimum

vertical or horizontal distance you can reduce either of the internal panels of the SplitContianer control.

Orientation

You use the Orientation property to specify the vertical or horizontal display of the

SplitContainer control.

IsSplitterFixed

You use the IsSplitterFixed property to specify whether the user must be able to

resize the panels at runtime by moving the splitter between the panels.

Suppose you want to add a vertical SplitContainer control to your Windows form. To do this, you first

create and declare the SplitContainer control in a subroutine that, in this case, handles the form's

Load event.

Page 62: 1_Windows Forms Creation With C# 2005

public class dynamicSplitContainer{ private void dynamicSplitContainer_Load(object sender, System.EventArgs e) { SplitContainer objSplitContainer = new SplitContainer(); }}

You then add the control to the form, specifying its size.

public class dynamicSplitContainer{ private void dynamicSplitContainer_Load(object sender, System.EventArgs e) { SplitContainer objSplitContainer = new SplitContainer(); this.Controls.Add(objSplitContainer); objSplitContainer.Size = new Size(160, 200); }}

In Design view, a vertical SplitContainer control with two panels – Panel1 and Panel2 – will be

applied to the form. This should only fully appear once you run your application and have applied a border to the control.

Next you want to configure the properties of the control, so as to specify in detail how it will display onscreen.

First you want to set the minimum and maximum distance between the SplitContainer panel and the

splitter bar on your form, so you set the Panel1MinSize and Panel2MinSize properties. In this case,

you want to be able to drag the splitter up to 40 pixels from the left edge of the container.

public class dynamicSplitContainer{ private void dynamicSplitContainer_Load(object sender, System.EventArgs e) { SplitContainer objSplitContainer = new SplitContainer(); this.Controls.Add(objSplitContainer); objSplitContainer.Size = new Size(160, 200); objSplitContainer.MISSING CODE;

Page 63: 1_Windows Forms Creation With C# 2005

}}

You type Panel1MinSize = 40 to complete the code.

You have set the Panel1MinSize property to 40 pixels.

public class dynamicSplitContainer{ private void dynamicSplitContainer_Load(object sender, System.EventArgs e) { SplitContainer objSplitContainer = new SplitContainer(); this.Controls.Add(objSplitContainer); objSplitContainer.Size = new Size(160, 200); objSplitContainer.Panel1MinSize = 40; }}

You want to be able to drag the splitter up to 50 pixels from the right edge of the container, so you set the Panel2MinSize property to 50.

objSplitContainer.Panel2MinSize = 50;

You want to set the location of the splitter to 70 pixels from the start of panel 1 – which given the current orientation is the left-hand border of the control.

public class dynamicSplitContainer{ private void dynamicSplitContainer_Load(object sender, System.EventArgs e) { SplitContainer objSplitContainer = new SplitContainer(); this.Controls.Add(objSplitContainer); objSplitContainer.Size = new Size(160, 200); objSplitContainer.Panel1MinSize = 40; objSplitContainer.Panel2MinSize = 50; objSplitContainer.MISSING CODE; }}

Page 64: 1_Windows Forms Creation With C# 2005

You type SplitterDistance = 70 to complete the code that sets the location of the splitter.

You have set the SplitterDistance property to 70.

public class dynamicSplitContainer{ private void dynamicSplitContainer_Load(object sender, System.EventArgs e) { SplitContainer objSplitContainer = new SplitContainer(); this.Controls.Add(objSplitContainer); objSplitContainer.Size = new Size(160, 200); objSplitContainer.Panel1MinSize = 40; objSplitContainer.Panel2MinSize = 50; objSplitContainer.SplitterDistance = 70; }}

You want to determine the amount of pixels the splitter is able to move at once, so you use the SplitterIncrement property to set the splitter to move in 3-pixel increments.

public class dynamicSplitContainer{ private void dynamicSplitContainer_Load(object sender, System.EventArgs e) { SplitContainer objSplitContainer = new SplitContainer(); this.Controls.Add(objSplitContainer); objSplitContainer.Size = new Size(160, 200); objSplitContainer.Panel1MinSize = 40; objSplitContainer.Panel2MinSize = 50; objSplitContainer.SplitterDistance = 70; objSplitContainer.MISSING CODE; }}

You type SplitterIncrement = 3 to complete the code.

You have set the splitter to move in 3-pixel increments.

Page 65: 1_Windows Forms Creation With C# 2005

public class dynamicSplitContainer{ private void dynamicSplitContainer_Load(object sender, System.EventArgs e) { SplitContainer objSplitContainer = new SplitContainer(); this.Controls.Add(objSplitContainer); objSplitContainer.Size = new Size(160, 200); objSplitContainer.Panel1MinSize = 40; objSplitContainer.Panel2MinSize = 50; objSplitContainer.SplitterDistance = 70; objSplitContainer.SplitterIncrement = 3; }}

The orientation of the objSplitContainer control is set at vertical by default. You want to set the

orientation to horizontal using the Orientation enumeration.

public class dynamicSplitContainer{ private void dynamicSplitContainer_Load(object sender, System.EventArgs e) { SplitContainer objSplitContainer = new SplitContainer(); this.Controls.Add(objSplitContainer); objSplitContainer.Size = new Size(160, 200); objSplitContainer.Panel1MinSize = 40; objSplitContainer.Panel2MinSize = 50; objSplitContainer.SplitterDistance = 70; objSplitContainer.SplitterIncrement = 3; objSplitContainer.Orientation = MISSING CODE; }}

You type Orientation.Horizontal to complete the code.

The objSplitContainer control will now display using a horizontal orientation. The minimum size of

either panel will now be measured from the top for Panel1 and the bottom for Panel2, rather than from left and right.

Public class dynamicSplitContainer{ private void dynamicSplitContainer_Load(object sender,

Page 66: 1_Windows Forms Creation With C# 2005

System.EventArgs e) { SplitContainer objSplitContainer = new SplitContainer(); this.Controls.Add(objSplitContainer); objSplitContainer.Size = new Size(160, 200); objSplitContainer.Panel1MinSize = 40; objSplitContainer.Panel2MinSize = 50; objSplitContainer.SplitterDistance = 70; objSplitContainer.SplitterIncrement = 3; objSplitContainer.Orientation = Orientation.Horizontal; }}

You now want to specify that users must be able to resize the SplitContainer at runtime. To do this,

you set its IsSplitterFixed property.

public class dynamicSplitContainer{ private void dynamicSplitContainer_Load(object sender, System.EventArgs e) { SplitContainer objSplitContainer = new SplitContainer(); this.Controls.Add(objSplitContainer); objSplitContainer.Size = new Size(160, 200); objSplitContainer.Panel1MinSize = 40; objSplitContainer.Panel2MinSize = 50; objSplitContainer.SplitterDistance = 70; objSplitContainer.SplitterIncrement = 3; objSplitContainer.Orientation = Orientation.Horizontal; objSplitContainer.BorderStyle = BorderStyle.FixedSingle; objSplitContainer.MISSING CODE; }}

You type IsSplitterFixed = false to complete the code.

You have fixed the position of the splitter in your SplitContainer control.

public class dynamicSplitContainer{ private void dynamicSplitContainer_Load(object sender,

Page 67: 1_Windows Forms Creation With C# 2005

System.EventArgs e) { SplitContainer objSplitContainer = new SplitContainer(); this.Controls.Add(objSplitContainer); objSplitContainer.Size = new Size(160, 200); objSplitContainer.Panel1MinSize = 40; objSplitContainer.Panel2MinSize = 50; objSplitContainer.SplitterDistance = 70; objSplitContainer.SplitterIncrement = 3; objSplitContainer.Orientation = Orientation.Horizontal; objSplitContainer.BorderStyle = BorderStyle.FixedSingle; objSplitContainer.IsSplitterFixed = false;

Finally, you create and add labels to both of the panels to clearly identify them to the user.

Label lblName = new Label(); Label lblAddress = new Label(); lblName.Text = "Name"; lblAddress.Text = "Address"; objSplitContainer.Panel1.Controls.Add(lblName); objSplitContainer.Panel2.Controls.Add(lblAddress); }}

The objSplitContainer control and its panels now display using the property values you've specified.

Question

Suppose you want to set the splitter on your SplitContainer control to move in

10-pixel increments.

Complete the code to do this.

public class mySplit{ private void dSC_Load(object sender, System.EventArgs e) { SplitContainer SC1 = new SplitContainer(); SC1.MISSING CODE; }}

Page 68: 1_Windows Forms Creation With C# 2005

Answer

To set the splitter on your SplitContainer control to move in 10-pixel

increments, you type

SplitterIncrement = 10

Question

Suppose you have added a SplitContainer control to a form and you want to

configure it to specify a location for a splitter on your form.

Which property should you use to do this?

Options:

1. Orientation

2. SplitterDistance

3. SplitterIncrement

Answer

To configure a SplitContainer control to specify a location for a splitter on your

form, you use the SplitterDistance property.

Option 1 is incorrect. The Orientation property is used to set the orientation of

the SplitContainer control to either vertical or horizontal on a form.

Option 2 is correct. The SplitterDistance property is used to determine the

location of the splitter on a form.

Option 3 is incorrect. The SplitterIncrement property is used to specify the

number of pixels a splitter must move at a time.

5. Adding a WebBrowser control

The WebBrowser control is a type of display control that enables users to navigate to web pages from a

Windows form. You can use this type of control to add browsing functionality to an application, so that users can view and download data.

Suppose you've already added a WebBrowser control, along with a text box labeled "Address" and a Go

button, to a form. You did this by double-clicking the controls in the Toolbox.

You now need to configure the WebBrowser control so that when a user enters a URL in the address bar

Page 69: 1_Windows Forms Creation With C# 2005

and clicks the Go button, the required web page will display in the control on the form. To do this, you need to add the appropriate code to the Button control's Click event. Then you want to load the

requested web page in the WebBrowser control.

Note The address bar and Go button are not part of the control – they are added for functionality

purposes.

To begin, you set the event handler for the button's Click event to invoke a user-defined method that

enables navigation to the resource identified by a URL.

public class frmWebBrowser{ private void btnGo_Click(object sender, System.EventArgs e) { MISSING CODE; }}

You type Navigate();.

When a user clicks the Go button – which is named btnGo – at runtime, the code you've written will now

invoke the Navigate method.

public class frmWebBrowser{ private void btnGo_Click(object sender, System.EventArgs e) { Navigate(); }

Next you create the subroutine and include an If statement to check that the user has included the prefix

http:// in the specified URL and – if not – to add this prefix. The prefix will be appended onto the beginning of the URL which is returned from a user-defined property named browserUrl.

private void Navigate(){ if (! (browserUrl.StartsWith("http://"))) { browserUrl = "http://" + browserUrl(); }

}}

Page 70: 1_Windows Forms Creation With C# 2005

You then write the code to actually load the requested web page in the WebBrowser control, which in this

case is also named WebBrowser.

public class frmWebBrowser{ private void btnGo_Click(object sender, System.EventArgs e) { Navigate(); }

private void Navigate() { if (! (browserUrl.StartsWith("http://"))) { browserUrl = "http://" + browserUrl(); }

MISSING CODE(new Uri(browserUrl));

}}

You type WebBrowser.Navigate to complete the code.

The document at the specified URL will now be loaded into the WebBrowser control.

public class frmWebBrowser{ private void btnGo_Click(object sender, System.EventArgs e) { Navigate(); }

private void Navigate() { if (! (browserUrl.StartsWith("http://"))) { browserUrl = "http://" + browserUrl(); }

WebBrowser.Navigate(new Uri(browserUrl));

}}

Page 71: 1_Windows Forms Creation With C# 2005

Finally, you create a new property to return the URL that a user has entered in the text box, and to store the text value of the specified address in a string format.

public class frmWebBrowser{ private void btnGo_Click(object sender, System.EventArgs e) { Navigate(); }

private void Navigate() { if (! (browserUrl.StartsWith("http://"))) { browserUrl = "http://" + browserUrl; }

WebBrowser.Navigate(new Uri(browserUrl));

}

private string browserUrl { get { return txtAddress.Text.Trim(); } set {

txtAddress.Text = value; } }}

You have now added and configured a WebBrowser control.

Question

Suppose you're currently configuring a WebBrowser control called

myOwnWebBrowser. You need to complete the code to load a requested web

page – based on a URL entered by the user at runtime – inside the WebBrowser

control.

Complete the code to do this.

Page 72: 1_Windows Forms Creation With C# 2005

public class myfrmW{ private void bNav_Click(object sender, System.EventArgs e) { Surf(); }

private void Surf() { if (! (location.StartsWith("http://"))) { location = "http://" + location(); }

MISSING CODE(new Uri(location));

}}

Answer

To complete the code that will load a specified web page inside the WebBrowser

control, you type

myOwnWebBrowser.Navigate

Summary

In Visual Studio 2005, you can use the Panel control as a simple container for other controls. If you

disable the control, all the controls it contains are disabled also. You use the GroupBox control to group

collections of controls logically – for example, to ensure that only one RadioButton control can be

selected from a collection at a time.

The TabControl control consists of tabbed pages, which you can use to contain other controls. To

configure the control, you add tabbed pages, add these pages to the TabControl container, and then

add the TabControl control to a form using the Add method.

You use the FlowLayoutPanel control to group other controls and to specify where each of the grouped

controls must display, based on a flow direction you specify. You can also choose to set controls in the container to wrap. You use the TableLayoutPanel control to display other controls in a grid-like

structure. You can use specific properties of the control to set the characteristics of specific rows or columns.

Page 73: 1_Windows Forms Creation With C# 2005

The SplitContainer control consists of two resizable panels, separated by a movable bar called a

splitter. You can use properties of the control to configure the size and resizing behavior of the panels, as well as the location of the splitter and the increments at which it can be moved.

The WebBrowser control is a display control that enables users to navigate to web pages from within a

form.

Creating a Basic Windows Form

Learning objective

After completing this topic, you should be able to add and group controls, and configure layout properties in a Windows Forms application.

Exercise overview

In this exercise, you're required to add and group controls, and configure layout properties of a form in a Windows Forms application.

This involves the following tasks:

adding and configuring a GroupBox control

adding controls to a form

setting a tab order for the controls on a form

setting borders and margins for a form

You're creating a Windows form to enable users to select options from an online restaurant menu. The form uses a tabbed page for each of three separate menus – for breakfast, lunch, and dinner.

The application will use a Button command control to enable users to submit their selections. The

individual food items will be listed using RadioButton controls.

Task 1: Configuring a GroupBox control

You have already created a menu form with a TabControl control consisting of three tabbed pages.

Now you want to add a GroupBox container control to your form, to enable you to group the command

controls you will add to the form at a later stage.

Step 1 of 2

You want to add a GroupBox control named GroupBox1 programmatically to the

first tabbed page – the Breakfast tabbed page – on your form.

Page 74: 1_Windows Forms Creation With C# 2005

Complete the code to do this.

public class Form1{ private void InitializeMyGroupBox() { GroupBox GroupBox1 = new GroupBox(); this.MISSING CODE; }}

Result

To complete the code that adds the GroupBox1 control to the first tabbed page on

the form, you type

Breakfast.Controls.Add(GroupBox1)

Step 2 of 2

After you have added the GroupBox control, you decide to customize the

container by changing its appearance to make it look slightly raised from the form's 2-dimensional surface.

Which line of code do you use to do this?

public class Form1{ private void InitializeMyGroupBox() { GroupBox GroupBox1 = new GroupBox(); MISSING CODE; this.Controls.Add(GroupBox1); }}

Options:

1. Panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

2. GroupBox1.Location = new Point(16, 16);

Page 75: 1_Windows Forms Creation With C# 2005

3. GroupBox1.FlatStyle = FlatStyle.Popup;

Result

To add a popup FlatStyle to the GroupBox, you use the code

GroupBox1.FlatStyle = FlatStyle.Popup

Option 1 is incorrect. This code creates a single border style using the FixedSingle property for a Panel control.

Option 2 is incorrect. This code sets the location of the GroupBox control on the

form.

Option 3 is correct. This code sets the GroupBox control's FlatStyle property

to Popup.

Task 2: Adding controls

Once you have added and configured a GroupBox container for the form, you want to add three

RadioButton controls and a Button control to the container.

Step 1 of 2

You first need to add a RadioButton control – named RadioButton1 – to the

GroupBox control.

Complete the code to do this.

public class Form1{ private void InitializeMyGroupBox() { GroupBox GroupBox1 = new GroupBox(); RadioButton RadioButton1 = new RadioButton(); GroupBox1.FlatStyle = FlatStyle.Popup; GroupBox1.Controls.MISSING CODE; this.Controls.Add(GroupBox1); }}

Result

Page 76: 1_Windows Forms Creation With C# 2005

To complete the code that adds the RadioButton1 control to the GroupBox

control, you type

Add(RadioButton1)

You add another two RadioButton controls – RadioButton2 and RadioButton3 – to the GroupBox

control.

public class Form1{ private void InitializeMyGroupBox() { GroupBox GroupBox1 = new GroupBox(); RadioButton RadioButton1 = new RadioButton(); RadioButton RadioButton2 = new RadioButton(); RadioButton RadioButton3 = new RadioButton(); GroupBox1.FlatStyle = FlatStyle.Popup; GroupBox1.Controls.Add(RadioButton1); GroupBox1.Controls.Add(RadioButton2); GroupBox1.Controls.Add(RadioButton3); this.Controls.Add(GroupBox1); }

Step 2 of 2

Once you have added the three RadioButton controls to the GroupBox, you

want to add a Button control – named Button1 – that will enable users to

submit the choice they make using the radio buttons.

Complete the code to do this.

public class Form1{ private void InitializeMyGroupBox() { Button Button1 = new Button(); GroupBox GroupBox1 = new GroupBox(); RadioButton RadioButton1 = new RadioButton(); RadioButton RadioButton2 = new RadioButton(); RadioButton RadioButton3 = new RadioButton(); GroupBox1.FlatStyle = FlatStyle.Popup; GroupBox1.Controls.Add(RadioButton1); GroupBox1.Controls.Add(RadioButton2); GroupBox1.Controls.Add(RadioButton3);

Page 77: 1_Windows Forms Creation With C# 2005

GroupBox1.MISSING CODE; this.Controls.Add(GroupBox1); }}

Result

To complete the code that adds the Button1 control to the GroupBox control,

you type

Controls.Add(Button1)

Task 3: Setting tab order

You now want to set the tab order for each of the controls you've added to the GroupBox control on your

form, so that when users tab between the controls, they are selected in the order – from top to bottom – in which they display on the form.

Step 1 of 2

You want to set the tab order for the RadioButton control so that this control

receives automatic focus, when the range is from one to four.

Complete the code to do this.

//RadioButton1 // this.RadioButton1.AutoSize = true; this.RadioButton1.Location = new System.Drawing.Point(7, 20); this.RadioButton1.Name = "RadioButton1"; this.RadioButton1.Size = new System.Drawing.Size(90, 17); this.MISSING CODE; this.RadioButton1.TabStop = true; this.RadioButton1.Text = "RadioButton1"; this.RadioButton1.UseVisualStyleBackColor = true; // //RadioButton2 // this.RadioButton2.AutoSize = true; this.RadioButton2.Location = new System.Drawing.Point(7, 44); this.RadioButton2.Name = "RadioButton2";

Page 78: 1_Windows Forms Creation With C# 2005

this.RadioButton2.Size = new System.Drawing.Size(90, 17); this.RadioButton2.TabStop = true; this.RadioButton2.Text = "RadioButton2"; this.RadioButton2.UseVisualStyleBackColor = true; // //RadioButton3 // this.RadioButton3.AutoSize = true; this.RadioButton3.Location = new System.Drawing.Point(7, 68); this.RadioButton3.Name = "RadioButton3"; this.RadioButton3.Size = new System.Drawing.Size(90, 17);

Result

To set the tab order for RadioButton1 to ensure that it will receive the first tab

focus on the form, you type

RadioButton1.TabIndex = 1

You complete the code to set the tab order for RadioButton2 to 2 and the tab order for RadioButton3

to 3.

//RadioButton2 // this.RadioButton2.AutoSize = true; this.RadioButton2.Location = new System.Drawing.Point(7, 44); this.RadioButton2.Name = "RadioButton2"; this.RadioButton2.Size = new System.Drawing.Size(90, 17); this.RadioButton2.TabIndex = 2; this.RadioButton2.TabStop = true; this.RadioButton2.Text = "RadioButton2"; this.RadioButton2.UseVisualStyleBackColor = true; // //RadioButton3 // this.RadioButton3.AutoSize = true; this.RadioButton3.Location = new System.Drawing.Point(7, 68); this.RadioButton3.Name = "RadioButton3"; this.RadioButton3.Size = new System.Drawing.Size(90, 17); this.RadioButton3.TabIndex = 3; this.RadioButton3.TabStop = true; this.RadioButton3.Text = "RadioButton3"; this.RadioButton3.UseVisualStyleBackColor = true;

Page 79: 1_Windows Forms Creation With C# 2005

Step 2 of 2

Last, you want to set the tab order for the Button1 control to ensure that it

receives the final tab focus on the form.

Which line of code do you use to do this?

// //Button1 // this.Button1.Location = new System.Drawing.Point(85, 120); this.Button1.Name = "Button1"; this.Button1.Size = new System.Drawing.Size(75, 23); MISSING CODE; this.Button1.Text = "Button1"; this.Button1.UseVisualStyleBackColor = true; // //RadioButton1 // this.RadioButton1.AutoSize = true; this.RadioButton1.Location = new System.Drawing.Point(7, 20); this.RadioButton1.Name = "RadioButton1"; this.RadioButton1.Size = new System.Drawing.Size(90, 17); this.RadioButton1.TabIndex = 1; this.RadioButton1.TabStop = true; this.RadioButton1.Text = "RadioButton1"; this.RadioButton1.UseVisualStyleBackColor = true; // //RadioButton2 // this.RadioButton2.AutoSize = true; this.RadioButton2.Location = new System.Drawing.Point(7, 44); this.RadioButton2.Name = "RadioButton2"; this.RadioButton2.Size = new System.Drawing.Size(90, 17);

Options:

1. this.Button1.TabIndex = 4

2. this.Button1.TabStop = 4

3. this.RadioButton1.TabIndex = 4

Page 80: 1_Windows Forms Creation With C# 2005

Result

To ensure that Button1 will receive the final tab focus on the form, you use the

code

this.Button1.TabIndex = 4

Option 1 is correct. This code sets the tab order for the Button control to 4 by

changing the TabIndex property in InitializeComponent.

Option 2 is incorrect. This code determines whether the user is able to use the tab key to give the Button control focus.

Option 3 is incorrect. This code sets the tab order for the RadioButton control to

4 rather than the Button control.

Task 4: Setting borders and margins

Finally, you want to configure the layout and appearance of the form.

Step 1 of 2

You've accessed the class code for the form in the code editor. You now want to configure the form to use a fixed border style that will prevent users from resizing the form at runtime.

Complete the code to do this.

public class Form1{ private void InitializeMyGroupBox() { Button1 Button1 = new Button1(); GroupBox GroupBox1 = new GroupBox(); RadioButton RadioButton1 = new RadioButton(); RadioButton RadioButton2 = new RadioButton(); RadioButton RadioButton3 = new RadioButton(); GroupBox1.FlatStyle = FlatStyle.Popup; GroupBox1.Controls.Add(RadioButton1); GroupBox1.Controls.Add(RadioButton2); GroupBox1.Controls.Add(RadioButton3); GroupBox1.Controls.Add(Button1); this.Controls.Add(GroupBox1);

Page 81: 1_Windows Forms Creation With C# 2005

}

private void Form1_Load(object sender, System.EventArgs e) { this.FormBorderStyle = Windows.Forms.MISSING CODE; }}

Result

To complete the code that configures the form to use a fixed border style that prevents resizing of the form at runtime, you type

FormBorderStyle.FixedDialog

Step 2 of 2

You have now accessed the InitializeComponent subroutine for the form in

the code editor. You want to ensure that the Button1 control on your form is kept

a certain distance – 6 pixels – away from the borders of other controls on the form.

Complete the code to do this.

// //Button1 // this.Button1.Location = new System.Drawing.Point(85, 120); this.Button1.Margin = new System.Windows.MISSING CODE; this.Button1.Name = "Button1"; this.Button1.Size = new System.Drawing.Size(75, 23); this.Button1.TabIndex = 4; this.Button1.Text = "Button1"; this.Button1.UseVisualStyleBackColor = true; // //RadioButton3 // this.RadioButton3.AutoSize = true; this.RadioButton3.Location = new System.Drawing.Point(7, 68); this.RadioButton3.Name = "RadioButton3"; this.RadioButton3.Size = new System.Drawing.Size(90, 17); this.RadioButton3.TabIndex = 3; this.RadioButton3.TabStop = true;

Page 82: 1_Windows Forms Creation With C# 2005

this.RadioButton3.Text = "RadioButton3"; this.RadioButton3.UseVisualStyleBackColor = true; // //RadioButton2 // this.RadioButton2.AutoSize = true; this.RadioButton2.Location = new System.Drawing.Point(7, 44); this.RadioButton2.Name = "RadioButton2";

Result

To complete the code to ensure that the Button1 control is kept at least 6 pixels

away from the borders of other controls on the form, you type

Forms.Padding(6)

A container control and command controls have been added to a form, the tab order for the controls has been set, and the appearance and layout of the form have been customized.

Composite Controls and Dialog Boxes in Windows Forms

Learning objective

After completing this topic, you should be able to identify how to create and configure composite Windows Forms controls and to create custom dialog boxes.

1. Composite Controls

Windows Forms controls can be combined to create other controls called Composite Windows Forms controls.

Note When you derive a composite control from System.Windows.Forms.UserControl, the

composite control is called a user control.

Composite controls are created to be reused and extended as needed, and can consist of any number of Windows Forms controls, components, or blocks of code that can extend the control's functionality. Controls that are placed into a composite control are known as constituent controls. Composite controls are placed onto forms the same way that other controls are.

Suppose you want to create a composite control that displays a DateTimePicker control and a Label control. To create the control, you need to

Page 83: 1_Windows Forms Creation With C# 2005

create a new control library

add the label and calendar controls

compile the control

add the control to the toolbox

add the control to a form

You first need to create a control library. To do so, you've already opened the New Project dialog box and selected Windows Control Library.

You name the control library CalendarControl. The name of the project is also assigned to the root namespace by default, and is used to qualify the names of components in the project assembly.

You then click OK to create the project.

The User Control design page is slightly different to a Windows Form. Instead of a form, you are presented with a control design box.

You start by renaming the UserControl1.cs file to CalendarControl.cs.

Then you resize the designer to ensure that the control fits inside it.

You want to add a label to the form.

You double-click Label in the toolbox.

C# adds a label named Label1 to the designer surface.

To complete the composite control, you add a DateTimePicker control.

You change the Text property of the label by typing DateTimePicker Control in the Text text box in

the Properties pane, and reposition both controls.

You want to edit the code for the DateTimePicker to display the DateTimePicker's value text in the label. You double-click the DateTimePicker control to edit the DateTimePicker_ValueChanged event.

public class CalandarControl{ private void DateTimePicker1_ValueChanged(object sender, System.EventArgs e) {

MISSING CODE

}}

Page 84: 1_Windows Forms Creation With C# 2005

You type Label1.Text = DateTimePicker1.Text; at the prompt.

After creating the control, you need to compile it in order to be able to add the control to the toolbox. If the control is part of a project or solution then it will be available in the toolbox once the control has been compiled.

To compile the control into an assembly for use with other projects you can use the commands under the Build menu in Visual Studio or you can run the C# compiler command – csc – from the directory that contains the control's source file. In this command, you specify the name of the output DLL file, which is automatically saved in the same directory.

csc /t:library /out:name.dll /r:System.Web.dll *.cs

You start the Visual Studio 2005 Command Prompt by selecting Start - Programs - Microsoft Visual Studio 2005 - Visual Studio Tools - Visual Studio 2005 Command Prompt.

By launching the Visual Studio 2005 Command Prompt you are configuring the PATH environment variable to allow you to use the C# compiler from any directory.

With the Visual Studio 2005 Command Prompt open, navigate to the directory in which the controls are located.

C:\CalendarControl\CalendarControl>

Then you use the csc command to compile the sources files into an assembly named CalendarControl.

csc /t:library /out:CalendarControl.dll *.cs

The system compiles the assembly and stores the DLL file in the same directory.

Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.42for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727Copyright (C) Microsoft Corporation 2001-2005. All rights reserved.

C:\CalendarControl\CalendarControl>

Finally, you close the Command Prompt window to return to Visual Studio.

exit

Once the CalendarControl component has been compiled it can be added to the Toolbox as a .NET Framework Component file.

You've already returned to design view, opened the Toolbox, and right-clicked it.

Page 85: 1_Windows Forms Creation With C# 2005

You select Choose Items, click Browse on the .NET Framework Components tabbed page of the Choose Toolbox Items dialog box, select the CalendarControl.dll file and click Open in the Open dialog box, and then click OK.

The Toolbox lists the control that was compiled in the assembly.

Once you've added a control to the toolbox, it stays there until you either delete it or reset the toolbox. To add the Calendar Control component to a new Windows form, you create a new Windows Application project and then either double-click the control in the Toolbox, or drag it onto the form.

Question

You've created a custom control called ctlClockLib that you want to add to a form, and to do so, you've already right-clicked the Tools menu.

How do you add the custom control to the form?

Options:

1. Select Choose Items, click Browse, select the ctlClockLib.dll file, click Open, click OK, and then double-click ctlClock in the Toolbox

2. Select Choose Items, select the COM Components tabbed page, click Browse, select the ctlClock.dll file, click Open, click OK, and then double-click ctlClock in the Toolbox

3. Select Choose Items, click Browse, select the ctlClock.dll file, click Reset, click OK, and then double-click ctlClock in the Toolbox

Answer

To add the custom control to the form, you select Choose Items, click Browse, select the ctlClockLib.dll file, click Open, click OK, and then double-click ctlClock in the Toolbox.

2. Properties, Events, and Methods

Windows Forms controls support the use of properties, methods, and events, and usually inherit these from the base class System.Windows.Forms.Control.

In addition to the pre-defined properties inherent to each control, Visual Studio enables you to create custom properties, methods, and events.

There are three important types of custom code that you can create:

Properties

Methods

Events

Page 86: 1_Windows Forms Creation With C# 2005

Properties

A Windows Forms control inherits numerous properties from the

System.Windows.Forms.Control base class. These inherited properties can be overridden

with your own defined properties.

There are generally two parts to a property definition:

The private data member is not always required in a property definition, but it enables you

to create a space to perform calculations should you require it. The syntax of a private data

member is

private DataType Variable(= Value)

You define public properties using the property declaration syntax. This syntax associates

the private data member with a public property through Get and Set accessor functions.

The property declaration enables you to store and retrieve values in a property, and forms

the core of the property definition. The syntax of the property definition code block is

Public DataType PropertyName

{

get

{ return Variable;

} set

{

Variable = Value;

}

}

When defining a custom property, you should keep three points in mind.

An attribute specifies metadata-related information for the property that you're defining.

When defining a custom property, you must define the property's attributes.

The Invalidate method redraws controls onscreen, and must be called if the property you're

defining can change the visual display of the control. The redraw occurs when the

Invalidate method calls the OnPaint method. If you make multiple Invalidate calls, a single call to OnPaint is made. Invalidate calls should be made from the set accessor method.

Type converters enable you to convert strings to object types. Common data types have

converters already associated with them. However, properties that are defined with custom

data-types require attributes that associate custom user interface (UI) type editors with that

property. The UI editor enables you to edit properties and data types.

The properties of constituent controls are normally declared to be private and can't be

Page 87: 1_Windows Forms Creation With C# 2005

accessed by developers.

You can expose the user properties of a constituent control by creating a public property in

the user control and using the Get and Set accessors of the desired property to read and

change the property of the constituent control.

For example, you might want to define a property called Title, which is a string and returns

a string value. The Get and Set accessors enable you to read from and write to the local

variables in the property.

The code being displayed is

public string Title {

get {

return this.Text;

}

set {

this.Text = Value;

}

}

Methods

A method is a block of code that performs a sequence of actions or calculations, and is

associated with either a class or an object. Visual Studio contains many pre-defined

methods in each of its namespaces.

The advantage of using methods is that they have access to private data structures within

objects and classes that aren't normally available.

You define your own method by creating the method signature which consists of a method

modifier, for example public or private, a return type, the method name, and a list of

parameters for the method. Methods that do not return a value will have a return type of

void. Parameters are listed along with their data type in the header following the method

name.

The syntax for defining a method is

[public|private] ReturnType MethodName(DataType parameter)

{

MethodCode

}

To use the method, you call it with its name and any parameters that it requires. For example, MyMethod(5) calls a method called MyMethod, and inserts the parameter with

Page 88: 1_Windows Forms Creation With C# 2005

a value of 5. For this to compile, the method will need to have been defined with a single parameter that takes in a type for which 5 is a valid value, such as Integer.

Events

Windows Forms controls inherit over 60 different events from

System.Windows.Forms.Control. However, should you need to add functionality to the

event, you can override the inherited functionality.

If you need to override an inherited event, then you should override the OnEventName

method rather than use Delegates.

Events are provided for through three interrelated elements, namely

The class that provides the event data is derived from System.EventArgs, and is called

EventNameEventArgs. Appropriate classes providing event data might already be defined,

so you might not need to create a new class.

Event delegates are usually named EventNameEventHandler. Appropriate delegates might

already be defined, so you might not always need to create a new event delegate.

The class that raises the event needs to provide an event declaration called EventName,

and it needs to provide a method that raises the event. This method should be called

OnEventName.

Events are created in classes through the event keyword. When the compiler encounters

the event keyword, a private data member is also created.

You need to determine when the event must be raised once you have completed defining

an event implementation. The event is raised by calling the OnEventName method.

If you need to handle an event that was raised in another class, you need to add delegate

methods to the event.

For example, to create an event called DataDeleted, you define a public event member in a class where you set the event member type to a System.EventHandler delegate.

The text in the code window is

public event EventHandler DataDeleted;

Question

Match the code fragment to its custom code type.

Options:

Page 89: 1_Windows Forms Creation With C# 2005

1. Event

2. Method

3. Property

Targets:

A. private void Animals(int legs)

B. public event EventHandler TooManyAnimals

C. public string Animals

Answer

The event starts with public event EventHandler TooManyAnimals, the

method starts with private void Animals (int legs), and the property

starts with public string Animals.

Custom events start with public event followed by the event name and then a

delegate type deriving from System.EventHandler and then the event

name.

Custom methods start with an access modifer then the keyword void, followed by

the name of the method and the parameters they accept. You use the method by calling its name and parameters, for example Animals(4).

Custom properties start with public, followed by the property name and property

data type. Custom properties use the Get and Set accessors to read and write data from and to the property.

Question

You want to expose a user property called BookSale.

Which line of code starts the exposed property?

Options:

1. private string BookSale

2. public string BookSale

3. BookSale int;

4. int BookSale;

Answer

The line of code that starts the exposed property declaration is public string

BookSale.

Page 90: 1_Windows Forms Creation With C# 2005

Option 1 is incorrect. Exposed properties need to be declared public in order for them to be exposed, so you wouldn't use a private declaration. It is the data

members that they manipulate that are given private access modifers.

Option 2 is correct. To expose a user property of a constituent control, you start the definition with public, followed by the name of the property, and then its data

type.

Option 3 is incorrect. The declaration of an exposed property must start with public, followed by the data type, and then name of the property. You can't start

the declaration with the name of the property.

Option 4 is incorrect. The definition of an exposed property starts with public,

and not data type. Starting a statement with data type means that you're

declaring a variable.

Question

You want to expose a user property of a control you've written. You want to name the property "Price", which accepts a monetary amount, and so you need to calculate values to two decimal points.

Complete the code to expose the property of the control.

MISSING CODE{ get { return discountPrice; } set { if (value >= 0) { discountPrice = value; } }}

Answer

You type public Decimal Price at the prompt.

Page 91: 1_Windows Forms Creation With C# 2005

3. Custom dialog boxes

You can create custom dialog boxes to use in the Windows Forms that you create.

Note Before creating a custom dialog box, you should first check whether there is a pre-

formatted dialog box in the .NET Framework that meets your requirements. The Framework contains pre-formatted dialog boxes for operations such as opening files, printing, and saving files.

You create a new form to use for a custom dialog box by selecting Project - Add New Item.

You add a new form to the project, and name it "dialogbox.cs". You click Add to create the new form. There are several properties that require changing, however, before you can use the form as a dialog box.

You want to adjust the form properties so that it can be used as a dialog box.

You click the FormBorderStyle property, and select FixedDialog.

In the form properties, you change the FormBorderStyle property to FixedDialog. This ensures the borders will not be sizable.

Because dialog boxes don't have the standard Windows form controls such as maximize and minimize buttons, you need to set the MaximizeBox and MinimizeBox properties to False.

You also need to set the ControlBox property to False to ensure that the dialog box contains no menu bars.

Finally, you add controls to the dialog box and adjust its size to ensure no scrollbars will be needed.

You can retrieve the results of a dialog box action from the originating form. You do this by referencing either the DialogResult property, or the result of a call to the ShowDialog method.

Suppose you want to link a custom dialog box you have created to a button click event. It extends the Form class and adds two properties named Title and Label. Label corresponds to a label you have

placed in the custom dialog box called lblText. When designing, it is a good idea to add buttons and

handlers if you want to register different return results.

private void cmdButton_Click(object sender, System.EventArgs e){

Having customized code for a dialog box, you move back to your main form and, after adding the new custom dialog box, double-click the button on the form to display the code for the button click event.

Page 92: 1_Windows Forms Creation With C# 2005

You want to store the result of what the user did with the dialog box and return that value in an instance of the DiaLogResult enumeration. This will have a value corresponding to buttons commonly seen in

dialog boxes, such as Yes, No, OK, Cancel, Retry, and Ignore.

private void cmdButton_Click(object sender, System.EventArgs e){ MISSING CODE;

You type System.Windows.Forms.DialogResult enmResults at the prompt.

The enmResults variable will contain the result of the user action in the dialog box.

private void cmdButton_Click(object sender, System.EventArgs e){ System.Windows.Forms.DialogResult enmResults;

You then set the custom new title text and label text properties for the custom dialog box, which you named dlgNew when adding it to the top-level form.

dlgNew.Title = txtTitle.Text; dlgNew.Label = txtLabel.Text;

You set the action of the user response to the dialog box to be stored in enmResults.

enmResults = dlgNew.ShowDialog(this);

Finally, you display a seperate message box with the result of the user's action, and a single OK button. This will only appear once the custom dialog box has been closed in some way. Since at the moment the only way to exit the dialog box is by closing it, this message will read "User clicked Cancel", the only possible value of enmResults.

MessageBox.Show(string.Format("User clicked {0}.", enmResults), string.Empty, MessageBoxButtons.OK);

}

}

Creating a custom dialog box:

public class MainToShowDialogBox : System.Windows.Forms.Form

Page 93: 1_Windows Forms Creation With C# 2005

{

    private void cmdButton_Click(object sender, System.EventArgs e)

    {

        System.Windows.Forms.DialogResult enmResults;

        dlgNew.Title = txtTitle.Text;

        dlgNew.Label = txtLabel.Text;

        enmResults = dlgNew.ShowDialog(this);

        MsgBox(string.Format("User clicked {0}.", enmResults),

        MsgBoxStyle.OkOnly);

    }

}

The complete code for creating a message box (above)

Question

You want to store the result of a user action of a dialog box, winNew, that displays

the results of an operation you've performed, dlgResults.

Create the code to store the results of a dialog box, winNew.

MISSING CODE;MessageBox.Show(string.Format("Program Canceled.", dlgResults), string.Empty, MessageBoxButtons.OK);

Answer

The code to create the message box and output the results of the user action is dlgResults = winNew.ShowDialog(this).

Question

You've created a new form for a Windows application, and you want it to be a dialog box.

Page 94: 1_Windows Forms Creation With C# 2005

How do you change the properties of the form so that it behaves like a dialog box?

Options:

1. Click the down-pointing arrow at the FormBorderStyle field, select FixedDialog, click the down-pointing arrow at the MaximizeBox field, select False, click the down-pointing arrow at the MinimizeBox field, select False, and finally click the down-pointing arrow at the ControlBox field, and select False

2. Click the down-pointing arrow at the KeyPreview field, select True, click the down-pointing arrow at the MaximizeBox field, select False, click the down-pointing arrow at the MinimizeBox field, select False, and finally click the down-pointing arrow at the RightToLeft field, and select Yes

3. Click the down-pointing arrow at the FormBorderStyle field, select FixedDialog, click the down-pointing arrow at the Locked field, select True, click the down-pointing arrow at the Enabled field, select False, and finally click the down-pointing arrow at the ControlBox field, and select False

4. Click the down-pointing arrow at the Localizable field, select True, click the down-pointing arrow at the MaximizeBox field, select False, click the down-pointing arrow at the MinimizeBox field, select False, and finally click the down-pointing arrow at the ShowIcon field, and select False

Answer

To make the form behave like a dialog box, you click the down-pointing arrow at the FormBorderStyle field, select FixedDialog, click the down-pointing arrow at the MaximizeBox field, select False, click the down-pointing arrow at the MinimizeBox field, select False, and finally click the down-pointing arrow at the ControlBox field, and select False.

Summary

Composite controls are a type of custom control that contain multiple other controls. You can configure composite controls and add them to the controls section of the toolbox for use in forms creation.

Windows Forms support the use of custom properties, methods, and events. You can expose a property of a constituent control in a composite control by using the public keywords. Custom methods are

created using the void keyword. Custom events use the event keyword.

Using Windows Forms, you can also create custom dialog boxes if one you require doesn't already exist within the .NET framework. Using dialog boxes, you can retrieve the value of the user's last action and output it.

Control Customization and Inheritance in Windows Forms

Page 95: 1_Windows Forms Creation With C# 2005

Learning objective

After completing this topic, you should be able to identify the code used to customize control graphical appearance and create controls through inheritance in Windows Forms applications.

1. Drawing a custom control

With Microsoft C#, you can customize the way a control displays in a Windows Form. User controls that inherit from the Control class must have code provided that enables C# to render the graphical

representation of the control.

User controls that inherit from the UserControl class or a Windows Forms class already have graphical

representations such as text boxes. However, you can override the representation and supply your own design.

When you customize the visual representation of a control, this is known as rendering the control. To render controls, Windows Forms uses the Graphics Device Interface (GDI) library.

The classes that enable access to the GDI+ are in the System.Drawing namespace and its

subnamespaces.

Rendering a control involves

providing the drawing functionality through the System.Windows.Forms.Control base class

using essential elements of the GDI graphics library to draw objects

drawing the region geometry

using procedures for freeing graphics resources

Drawing functionality in C# is provided by the Paint event in the Control base class. Controls raise the

Paint event every time the display needs to update.

The PaintEventArgs event data class for the Paint event contains both types of data needed to draw

a control, namely

a handle to the graphics object

a rectangle object that represents a region to draw the control in, contained in the

System.Drawing.Rectangle class

Rendering logic is provided by the control by overriding the OnPaint method. OnPaint is able to access

graphics objects and a rectangle to draw in. This is done through the Graphics and ClipRectangle

properties of the PaintEventArgs instance that is passed to OnPaint. The OnPaint method doesn't

itself confer any drawing functionality, rather it enables you to call event delegates that are registered with the Paint event.

Page 96: 1_Windows Forms Creation With C# 2005

Overriding the OnPaint method typically should invoke its method in the base class so that the

registered delegate receives the paint event.

Note OnPaint should not be directly called from within the control. You must rather call the

Invalidate method which invokes OnPaint, or use a method that calls Invalidate, which in

turn calls OnPaint.

You may want only the background shape of the window instead of the details of the control. To do so, you use the OnPaintBackground method, which is fast, but can't draw details.

OnPaintBackground is useful, however, if you want to draw a control background with a color gradient

instead of flat color.

Note OnPaintBackground, though it uses the same structure as an event, is not a true event

method; there is no PaintBackground event, and OnPaintBackground doesn't invoke event

delegates.

The GDI+ library contains the Graphics class, which provides methods for C# to draw lines, shapes

such as ellipses and rectangles, and methods for displaying text.

However, before you draw, you need to specify the rectangular region that you'll use to draw in. The ClipRectangle property of the PaintEventArgs method specifies the area that will be painted.

Finally, after you've drawn the user control, you need to free the graphic resources you've used. If you create graphical objects that implement the IDispose interface, you should call its Dispose method

when you are done with it.

Suppose you want to draw a customized control by overriding the OnPaint method of the UserControl

class. To do so, you've already created a new custom control cs file.

MISSING CODE(PaintEventArgs e)

You type protected override void OnPaint at the prompt.

The declaration sets up an overridden OnPaint method that you want to use to draw controls. Controls

that override the OnPaint method are invisible before you compile them because the designer doesn't

automatically know how to render them.

protected override void OnPaint(PaintEventArgs e)

You then set up variables that will handle the brushes and various drawing tools that you use to draw the custom controls.

protected override void OnPaint(PaintEventArgs e){

Page 97: 1_Windows Forms Creation With C# 2005

Graphics graphics = e.Graphics; Pen pen = new Pen(Color.Black, 4f); int penWidth = 4; int fontHeight = 10; SolidBrush textBrush1 = new SolidBrush(Color.Black); Font font = new Font("Arial", fontHeight); graphics.DrawString("Text", font, textBrush1, penWidth, Height / 2 - fontHeight); SolidBrush textBrush2 = new SolidBrush(Color.Red);

You now want to draw an ellipse on the form.

protected override void OnPaint(PaintEventArgs e){ Graphics graphics = e.Graphics; Pen pen = new Pen(Color.Black, 4f); int penWidth = 4; int fontHeight = 10; SolidBrush textBrush1 = new SolidBrush(Color.Black); Font font = new Font("Arial", fontHeight); graphics.DrawString("Text", font, textBrush1, penWidth, Height / 2 - fontHeight); SolidBrush textBrush2 = new SolidBrush(Color.Red); MISSING CODE(testBrush2, 0, 0, Width, Height);

You type graphics.FillEllipse at the prompt.

The FillEllipse method enables you to draw an ellipse on the form using a specified brush.

protected override void OnPaint(PaintEventArgs e){ Graphics graphics = e.Graphics; Pen pen = new Pen(Color.Black, 4f); int penWidth = 4; int fontHeight = 10; SolidBrush textBrush1 = new SolidBrush(Color.Black); Font font = new Font("Arial", fontHeight); graphics.DrawString("Text", font, textBrush1, penWidth, Height / 2 - fontHeight); SolidBrush textBrush2 = new SolidBrush(Color.Red); graphics.FillEllipse(textBrush2, 0, 0, Width, Height);

The FillEllipse method accepts a brush specification, a pair of coordinates, and a width and height

specification, which defines a rectangular border within which an ellipse will be drawn and filled. This method also supports an overloaded version that accepts a Rectangle structure instead of these points.

Page 98: 1_Windows Forms Creation With C# 2005

You change brush styles and finally draw one last ellipse before closing the overridden method.

protected override void OnPaint(PaintEventArgs e){ Graphics graphics = e.Graphics; Pen pen = new Pen(Color.Black, 4f); int penWidth = 4; int fontHeight = 10; SolidBrush textBrush1 = new SolidBrush(Color.Black); Font font = new Font("Arial", fontHeight); graphics.DrawString("Text", font, textBrush1, penWidth, Height / 2 - fontHeight); SolidBrush textBrush2 = new SolidBrush(Color.Red); graphics.FillEllipse(textBrush2, 0, 0, Width, Height); graphics.DrawEllipse(pen, System.Convert.ToInt32(penWidth / 2), System.Convert.ToInt32(penWidth / 2), Width - penWidth, Height - penWidth);}

Question

You want to draw a custom control for use in an application.

Complete the code needed to create an overridden OnPaint method.

protected override void OnPaint( MISSING CODE)

Answer

The OnPaint method declaration is protected override void

OnPaint( PaintEventArgs e).

2. Customizing control appearances

C# enables you to alter the way a control displays in a number of ways, including, but not limited to

using visual styles

making controls invisible at runtime

rendering a control with a transparent background

The .NET framework enables you to use visual styles when you render controls and other Windows Forms interface elements. Visual styles will work only in operating systems that support them.

Page 99: 1_Windows Forms Creation With C# 2005

The System.Windows.Forms namespace includes classes that render parts and states of controls with

visual styles. Each class includes static methods that enable you to draw controls or parts of controls in the OS's visual style.

To enable visual styles, the System.Windows.Forms.Application.EnableVisualStyles()

method can be used.

Some classes draw controls irrespective of whether visual styles are available or not. The classes use styles if they are supported, otherwise the standard Windows Classic style is used. These classes include

ButtonRenderer

CheckBoxRenderer

GroupBoxRenderer

RadioButtonRenderer

Other classes draw the control only when visual styles are available, and throw exceptions if styles are disabled, aren't available, or are not supported. These classes include

ComboBoxRenderer

ProgressBarRenderer

ScrollBarRenderer

TabRenderer

TextBoxRenderer

TrackBarRenderer

There are two main classes of the System.Windows.Forms.VisualStyles:

VisualStyleElement

VisualStyleRenderer

VisualStyleElement

The VisualStyleElement class is a foundation class that enables you to identify

controls or user interfaces that support visual styles.

VisualStyleRenderer

The VisualStyleRenderer class contains the methods that enable you to draw and

obtain information about the VisualStyleElement that is defined by the current visual

style of the OS. VisualStyleRenderer information includes an element's size,

background type, and color definitions.

The following conditions must exist for the RenderWithVisualStyles property of the Application class

to return a value of true. These conditions are

the OS supports visual styles

the user enables visual styles in the OS

Page 100: 1_Windows Forms Creation With C# 2005

visual styles have been enabled in the application

visual styles are used to draw the client area of the application windows

the OS supports visual styles

You can verify if the OS supports visual styles by using the IsSupportedByOS property

of the VisualStyleInformation class.

the user enables visual styles in the OS

You can verify if the OS has enabled visual styles by using the IsEnabledByUser

property of the VisualStyleInformation class.

visual styles have been enabled in the application

Visual styles can be enabled in the application either by calling the System.Windows.Forms.Application.EnableVisualStyles() method or by

using an application manifest that specifies ComCtl32.dll version 6 or later is being used to

draw the controls.

visual styles are used to draw the client area of the application windows

You can verify if the client areas of the application windows were drawn using visual styles by using the VisualStyleState property of the Application class. You should verify

that it contains either System.Windows.Forms.VisualStyles.VisualStyleState.ClientAreaEnable

d or

System.Windows.Forms.VisualStyles.VisualStyleState.ClientAndNonClie

ntAreasEnabled.

If you need to use VisualStyleRenderer to render a control or user interface element when the user

enables or switches visual styles, you should use the UserPreferenceChanged instead of the

UserPreferenceChanging event, because UserPreferenceChanging throws an exception in this

case.

You can opt to make controls invisible at runtime, and change their visibility later on.

To be able to make a control invisible at runtime, you use the Visible property of the control.

By default, transparent backgrounds aren't supported by C# controls, but you can enable the effect using the SetStyle method of the Control class.

The SetStyle method can make controls opaque, transparent, or semi-transparent.

To make controls transparent, you

locate the constructor for the control class

call the SetStyle method

set the control back color to transparent

locate the constructor for the control class

Page 101: 1_Windows Forms Creation With C# 2005

You need to locate the constructor for the control class you use, which is a method with

the same name as the control, but with no return value.

call the SetStyle method

After you've located the control class constructor, you need to call the SetStyle method to

enable transparency on the control. To use the SetStyle method, you use this syntax:

SetStyle(ControlStyles.SupportsTransparentBackColor, true)

set the control back color to transparent

Beneath the line that locates the constructor for the control class, you add this line:

this.BackColor = Color.Transparent;

If you want to create partially transparent colors, you can use the FromArgb method.

Suppose you want to make a control invisible.

private void Button1_Click(object sender, System.EventArgs e) { MISSING CODE;

}}

You type Button1.Visible = false at the prompt.

The code instructs C# to make the button invisible when it is clicked.

private void Button1_Click(object sender, System.EventArgs e) { Button1.Visible = false;

}}

Suppose you have a form on which you want controls named btn_bitmap and btn_transparent to

appear as transparent when clicking on the latter control. You have set the UseVisualStyles property

for both of these controls to false in the designer. You begin with a handler for the button's click

event, which refreshes a PictureBox named pb_showimage and calls a user-defined method.

private void btn_transparent_Click(object sender, System.EventArgs

Page 102: 1_Windows Forms Creation With C# 2005

e){ pb_showimage.Refresh(); UseTransparentProperty();}

You intend the controls to be superimposed over pb_showimage. To do this, you set the image for it to

display and stretch it over the PictureBox, then set the PictureBox as the parent container for the

controls.

private void UseTransparentProperty(){

try { pb_showimage.Image = Image.FromFile("E:\\FN.jpg"); pb_showimage.SizeMode = PictureBoxSizeMode.StretchImage; MISSING CODE = pb_showimage;

You type btn_transparent.Parent at the prompt.

Having accomplished this for both controls, you then want to set the background color of the control to transparent.

private void UseTransparentProperty(){

try { pb_showimage.Image = Image.FromFile("E:\\FN.jpg"); pb_showimage.SizeMode = PictureBoxSizeMode.StretchImage; btn_transparent.Parent= pb_showimage; btn_bitmap.Parent = pb_showimage;

MISSING CODE;

You type btn_transparent.BackColor = Color.Transparent at the prompt.

The Color.Transparency enumeration value is assigned to the backcolor of the controls. At runtime,

the background color of the control on the form is transparent, and anything beneath the control is visible.

private void UseTransparentProperty()

Page 103: 1_Windows Forms Creation With C# 2005

{

try { pb_showimage.Image = Image.FromFile("E:\\FN.jpg"); pb_showimage.SizeMode = PictureBoxSizeMode.StretchImage; btn_transparent.Parent= pb_showimage; btn_bitmap.Parent = pb_showimage;

btn_transparent.BackColor = Color.Transparent;

Finally, you add the code to enable the bitmap background color to become transparent, add a condition for the file not being found, and end the code.

btn_bitmap.BackColor = Color.Transparent;

} catch (System.IO.FileNotFoundException ex) { MessageBox.Show("There was an error." + "Make sure the image file path is valid."); }}

At runtime, after clicking the button, the backgrounds of the buttons on the form become transparent and display the colors of the image beneath.

Question

Suppose you want to set a label, lblInfo, to be invisible at runtime, and display

only when needed.

Make the label control invisible.

private void Button1_Click(object sender, System.EventArgs e) { MISSING CODE;

}}

Answer

Page 104: 1_Windows Forms Creation With C# 2005

To set a label control to be invisible at runtime, you type lblInfo.Visible =

false at the prompt.

Question

Suppose you want to make the background of a label control named MyOwnLabel

transparent so that you can see a picturebox named MyPic beneath it. You've

already set the style of the control to support transparent colors.

Set the control's background to a transparent color.

public void MakeTransparent(){ MyOwnLabel.Parent = MyPic; MISSING CODE;}

Answer

To set a control's background to be transparent, you type MyOwnLabel.BackColor = Color.Transparent.

3. User control inheritance

C# enables you to create custom controls using inheritance, which means that the control retains the functionality of a standard Windows Forms control while incorporating functionality that you've added.

For example, you can create a control that is identical to a standard Windows Forms control, but exposes custom properties.

When a control inherits from an existing control, it inherits every function and visual property of the original control.

For example, if you created a control that inherited from a checkbox, the newly created control would display and behave exactly like a checkbox. You then extend or modify the new control by implementing custom methods and properties, or by changing the way the control displays.

If you want to modify the appearance of a control, you can use the OnPaint method to do so.

Note The OnPaint method won't work on all controls. Some controls, such as the TextBox, are

drawn by Windows, not by the OnPaint method. When the control runs, the custom code is

never called, and the control's custom appearance is never redrawn.

Page 105: 1_Windows Forms Creation With C# 2005

You can elect to create a custom control completely without relying on an existing control. To do so, you need to inherit from the Control class instead.

Doing so requires more planning and implementation, but you also have access to a wider range of options when building your control.

Inheriting from the Control class means that a control inherits the basic functionality behind controls

such as user input, keyboard and mouse events, defining control boundaries, providing window handles, and provision of message handling and security.

However, the Control class doesn't confer any painting ability nor specific user interaction, both of

which must be provided through code.

Suppose you want to create a new custom control that inherits from the TextBox class.

[ToolboxBitmap("E:\\TextBoxClass.bmp")]internal class TextboxClass MISSING CODE

You type : TextBox and press Enter.

The new class inherits from the TextBox class.

[ToolboxBitmap("E:\\TextBoxClass.bmp")]internal class Textbox Class : TextBox

You then customize the custom class to vary from the original class. In this case, you vary the text color of the class.

public Color MyBackColor = Color.Violet;

internal System.Windows.Froms.TextBox TextBox1;

Question

You want to create a control that has the exact visual components and functionality as a label, and then expose its properties to customize it.

Type the line of code that will enable a custom control to have the visual and functional components of a label.

Page 106: 1_Windows Forms Creation With C# 2005

[ToolboxBitmap("E:\\TextBoxClass.bmp")]internal class TextBoxClass MISSING CODE

Answer

To enable a custom control to inherit a label's functionality and visual appearance, you type : Label at the prompt.

Question

You want to develop a control that inherits from the Control class. Which

functionality does the Control class provide you?

Options:

1. Control size and boundaries

2. Paint functions

3. Specific user interactions

4. Window handles

Answer

The Control class provides functionality for control sizes and boundaries, and

window handles.

Option 1 is correct. The Control class provides a way to set the sizes and

boundaries of custom controls that you create.

Option 2 is incorrect. The Control class doesn't provide any paint functions, so

you need to draw the controls through custom code.

Option 3 is incorrect. The Control class only provides broad user input

functionality through the keyboard and mouse, but doesn't enable any specific user interactions such as clicking.

Option 4 is correct. The Control class provides functionality for window handles.

4. Custom control icons

You can specify that an icon of your choice appears in the toolbox when you compile a control and reference it in the toolbox.

Page 107: 1_Windows Forms Creation With C# 2005

You specify an image file using the ToolboxBitmapAttribute class. This attribute class accepts a

string value that indicates the path and filename of a 16x16 pixel bitmap file, which appears next to the control's name.

[ToolboxBitmap("locationstring")]internal class ClassName{//...}

You can also specify a Type that the bitmap will be associated with when that type is loaded. If you specify both a string and a type, then the control will search for an image with the name in the string parameter in the assembly that contains the type in the Type parameter.

[ToolboxBitmap(typeof(ClassName), "ImageName")]internal class ClassName{//...}

Suppose you want to specify a bitmap for your control.

[MISSING CODE("E:\\TextBoxClass.bmp")]internal class TextBoxClass : TextBox{ //...}

You type ToolboxBitmap at the prompt and press Enter.

The code specifies the location of the bitmap to use as a control image in the toolbox.

When you compile the control and reference it, the bitmap icon that you specified is used instead of the default control icon.

Question

You want to provide a custom bitmap for a control you've created, and you want the bitmap to appear in the toolbox when you compile the control.

Add the code that will insert the custom bitmap, Customclass.bmp, into the toolbox when the control is compiled.

Page 108: 1_Windows Forms Creation With C# 2005

[MISSING CODE("E:\\Customclass.bmp")]internal class TextBoxClass{ //...}

Answer

To insert the custom bitmap Customclass.bmp into the toolbox when the control is compiled, you add the code ToolboxBitmap

Summary

Microsoft C# enables you to change the visual appearance of controls. You can do this by drawing your own control using the OnPaint method and the PaintEventArgs event data class.

You can also adjust the appearance of a control by forcing it to comply or not comply with the OS visual styles, by rendering it invisible at runtime, and by rendering it with a transparent background.

The appearance and function of a control can be inherited from an existing Windows Forms control. You can then customize the inherited control by exposing the properties you want to customize.

Controls that you compile and reference in the toolbox can have their own icons associated with them in the toolbox. The icon should be a 16x16 bitmap.

Creating an Inherited Windows Forms Composite Control

Learning objective

After completing this topic, you should be able to create and customize an inherited composite control in a Windows Forms application, given a scenario.

Exercise overview

In this exercise, you're required to customize the contents and rendering of a composite control.

This involves the following task:

configuring a composite control

Page 109: 1_Windows Forms Creation With C# 2005

Task 1: Configuring a composite control

Suppose you want to design a complex fill-in form that will be used to input customers' address details. You want to use this form for several projects, so you decide to develop it as a reusable composite control.

In Design view, you add the following controls to the composite control:

labels and text boxes for capturing the name, address, and post code

a drop-down list box containing a list of states

a label associated with the drop-down list box, indicating the tax rate charged by the selected state

Step 1 of 5

When a user selects an item from the drop-down list box, its event handler updates the lblTax label with the appropriate tax amount. You want to add a

TaxRate property to the control, so users can retrieve the current tax rate from

the label or set the rate manually.

Complete the code to do this.

public class AdressCC{

MISSING CODE { get { return lblTax.Text; } set { lblTax.Text = value; } }

}

Result

You type public string TaxRate to complete the property declaration.

Step 2 of 5

Page 110: 1_Windows Forms Creation With C# 2005

The control you are creating will have a customized design, so you need to configure how it is rendered.

Complete the declaration of the method you need to override, using e as the

naming convention of the proper event argument parameter.

}}

protected override void MISSING CODE{

}

Result

You type OnPaint(PaintEventArgs e) to complete the declaration of the

method you have to override.

Step 3 of 5

The composite control you have created will be placed on a form that has an image background. You want to set a transparent background for the control so that it does not obscure the image behind it.

Complete the command that enables the control to support a transparent background.

private void UseTransparentProperty(){

try { pb_showimage.Image = Image.FromFile("H:\\images\\background.jpg"); btn_trans.Parent= pb_showimage;

MISSING CODE; } catch (FileNotFoundException ex) { //...

Page 111: 1_Windows Forms Creation With C# 2005

}}

Result

To complete the line of code that enables the control to support a transparent background, you type

btn_trans.BackColor = Color.Transparent

Step 4 of 5

You want to create a customized Submit button that you can add to the composite control. The button extends the features of the Button class by providing a

highlight when the user hovers over it. You are now creating a new class file for this SubmitButton control.

Provide the line of code to extend the Button class.

public class SubmitButton MISSING CODE{ private void SubmitButton_MouseEnter(object sender, System.EventArgs e) { this.ForeColor = SystemColors.ButtonHighlight; }

private void SubmitButton_MouseLeave(object sender, System.EventArgs e) { this.ForeColor = Color.Black; }

}

Result

You type : Button to extend the Button class.

After customizing the Submit button, you build the project and add the extended control to the composite control you have created. You then save the project file.

Step 5 of 5

Page 112: 1_Windows Forms Creation With C# 2005

You want to make the composite control – named AddressCC – available to other

projects. You will be compiling it to a dynamic linked library of the same name.

Complete the command to compile the control using the C# 2005 Command Prompt.

C:\AddressCC>MISSING CODE *.cs

Result

To complete the command to compile the control, you type

csc /t:library /out:AddressCC.dll

A composite control has been developed.

C:\AddressCC>csc/t:library/out:AddressCC.dll *.csMicrosoft (R) Visual C# 2005 Compiler version 8.00.50727.42for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727Copyright (C) Microsoft Corporation 2001-2005. All rights reserved. C:\AddressCC>

Event Handlers, Modifier Keys, and Overriding

Learning objective

After completing this topic, you should be able to identify how to create event handlers, program a Windows Forms application to recognize modifier keys, and override base methods, given a scenario.

1. Windows Forms event handlers

Windows Forms applications are ideal for event-driven programs, which means that an application's logic occurs in response to events.

An event is a signal sent by an object within an application to notify the application that something has happened to the object and it requires a response.

Events are usually initiated through a user action, program code, or by the system. They include actions such as mouse clicks, form loading, and keyboard presses.

Page 113: 1_Windows Forms Creation With C# 2005

When an event occurs, it is raised by the application, which then uses delegates to call an associated event handler to respond to the raised event.

Delegates are objects that point to separate event handlers. An event handler is a method that provides the code that responds to a raised event. The code specifies the actions the application should take to respond to the event.

An event handler is defined and added using specific syntax. The syntax you use to add an event handler is: ObjectName.EventName += new System.EventHandler(ObjectName_EventName);Meanwhile, the basic syntax you use to define an event handler is: private void ObjectName_EventName(object sender, System.EventArgs e){ //implementation}

ObjectName_EventName

(object sender, System.EventArgs e)

ObjectName.EventName +=

ObjectName_EventName

You need to specify a name for the event handler that follows the naming convention for

event handlers – ObjectName_EventName. The ObjectName should be the same as the name

of the control and the EventName should reflect the type of action triggered. So for example, an event handler that handles the Click event for a button control named btnShow should

be named btnShow_click.

(object sender, System.EventArgs e)

This is known as the event handler's method signature. The first parameter, sender, that

you pass to the event handler represents the object that raised the event. The sender object is usually of the super class type System.Object.

The second parameter, e, represents an object of type EventArgs. EventArgs, which is

a base class containing event data. You need to specify the specific EventArgs class for

an event when you want to access the properties of the event. For example, to handle a KeyPress event you need to specify the KeyPressEventArgs object in the event

handler.

ObjectName.EventName +=

You use the += operator to specify the event that is to be handled by the event handler.

For example, to indicate that the handler should respond to the Click event of a button

control called button1, you specify the event as button1.Click +=.

Question

When defining the method signature of an event handler, the first parameter it accepts is the sender.

What does this parameter hold?

Page 114: 1_Windows Forms Creation With C# 2005

Options:

1. An object containing event data

2. An object of the control that raised the event

3. The event to be handled

Answer

The sender parameter holds an object of the control that raised the event.

Option 1 is incorrect. The second parameter in an event handler's method signature – usually declared as e – contains an object of the EventArgs class,

which holds event data.

Option 2 is correct. The first parameter of the method signature, sender, contains

an object of the control that raised the event and is derived from the super class type System.Object.

Option 3 is incorrect. The event to be handled is specified in the += clause when

defining an event handler, and not in its method signature.

In Windows Forms applications there are several types of event handlers you can create, some of which include

default event handlers

keyboard event handlers

mouse event handlers

default event handlers

A default event handler is automatically created for a control on a form when you double-

click the control. However, this event type changes from control to control. For example, if you double-click a button control, a default event handler is created for the button's Click

event. However, if you click on a control such as a list box, a handler is created for its default event – SelectedIndexChanged.

keyboard event handlers

Keyboard event handlers are created to respond to key presses. The events that occur when a user presses a key are KeyDown, KeyPress, and KeyUp. The KeyDown event

occurs when a user pushes a key, the KeyPress event when the user holds the same

key, and KeyUp when the user releases the key. The event handlers for both the KeyDown

and KeyUp events accept the KeyEventArgs parameter, whereas the event handler for

the KeyPress event accepts the KeyPressEventArgs parameter.

mouse event handlers

Mouse event handlers are created to respond to mouse actions for a form, such as the

click of a button or moving the mouse over a label. Events raised with mouse actions

Page 115: 1_Windows Forms Creation With C# 2005

include MouseDown, Click, MouseClick, MouseUp, and MouseEnter. The MouseDown

event occurs as the mouse pointer is over a control while its button is pressed. The Click

and MouseClick events handle the moment the control is clicked and released, while the

MouseUp event occurs only as the button is released over a control. MouseEnter occurs

when the mouse pointer enters a control. Most mouse events accept the MouseEventArgs parameter, though MouseEnter accepts the normal EventArgs

object.

Sometimes you may have two or more controls that display the same functionality, such as a menu command and a button on a form. Instead of creating two event handlers, you can create a single event handler that handles multiple events. The event handler is then notified if any one of the associated events occurs.

To create a multiple control event handler, you need to specify the events you want handled with the +=

operator and use an EventHandler delegate, passing in the name of your event handler method. You

can only combine events into one handler if they all share the same EventName.

ControlName.EventName += new System.EventHandler(ObjectName_EventName);ControlName1.EventName += new System.EventHandler(ObjectName_EventName);

Controls that are dynamically created at runtime can be associated with dynamic event handlers. Dynamic event handlers are created at runtime to handle events based on code that executes at runtime and not on the application's initial load.

To create a dynamic event handler, you create a method similar to a regular event handler, which includes the event handler's method signature .

private void VariableName_EventName(object sender, System.EventArgs e){

event handler code;

}

Then within a method within the form's class you need to specify the event handler that will be handling the event using the += statement. The += statement connects an event to a specified event handler at

runtime. It consists of an += clause that specifies the name of the event to be handled and an System.EventHandler clause that specifies the name of the procedure or method that will handle the

event.

event += new System.EventHandler(eventhandler);

Page 116: 1_Windows Forms Creation With C# 2005

2. Creating Windows Forms event handlers

Say you want to create a default event handler for the Click event of a button control on a form. The

button name is Button1 and its text property is labeled "Change Color" in the form's Design view. When

the user clicks the button it should change the background color of a label – called lblMessage – on the

form to brown.

In the form's Design view, you double-click the button control.

A default event handler is created for the Button1 control's click event. Visual Studio automatically

creates the method signature of the event handler.

private void Button1_Click(object sender, System.EventArgs e) {

}}

You add the code within the event handler that will change the background color of the label, in this case lblMessage, to brown when the button is clicked.

private void Button1_Click(object sender, System.EventArgs e) { lblMessage.BackColor = Brown; }}

Say you want to create an event handler that handles the MouseDown event of a label – lblMessage –

on a form. When the user presses the mouse button over the top of the label, the background color of the label changes to yellow.

using System.Drawing.Color;

public class frmMouseKeyBoardEvents : System.Windows.Forms.Form

Note You need to import the System.Drawing.Color namespace to access methods and

properties of the Color class.

You need to specify from which EventArgs class the event handler will receive event data for the

MouseDown event.

Page 117: 1_Windows Forms Creation With C# 2005

using System.Drawing.Color;

public class frmMouseKeyBoardEvents : System.Windows.Forms.Form{

private void lblMessage_MouseDown(object sender, System.Windows.Forms.MISSING CODE e) {

lblMessage.BackColor = Color.Yellow; }}

You type MouseEventArgs to specify the appropriate EventArgs class and you press Enter.

You've created an event handler for the MouseDown event.

using System.Drawing.Color;

public class frmMouseKeyBoardEvents : System.Windows.Forms.Form{ private void lblMessage_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) {

lblMessage.BackColor = Color.Yellow; }}

Question

You want to create an event handler that handles the MouseEnter event for a

label on a form. You want the second parameter, e, in the method signature to

receive event data from the base class of the System namespace.

Type the code to do this.

using System.Drawing.Color;

public class frmMouseKeyBoardEvents : System.Windows.Forms.Form{ private void lblMessage_MouseEnter(object sender, MISSING

Page 118: 1_Windows Forms Creation With C# 2005

CODE e) {

lblMessage.BackColor = Color.Red; }}

Answer

The code to receive event data from the base class of the System namespace is

System.EventArgs or simply EventArgs.

Suppose you want to use an event handler to make a label on the base form visible – using the F1 key –

and invisible – using the ESC key. When the user releases either key the event handler should be called and the appropriate action taken.

using System.Drawing.Color;

public class frmMouseKeyBoardEvents : System.Windows.Forms.Form

You want to write an event handler for the KeyUp event. It will use the KeyCode property of the KeyEventArgs object to determine which key the user has released.

using System.Drawing.Color;

public class frmMouseKeyBoardEvents : System.Windows.Forms.Form

{ private void frmMouseKeyBoardEvents_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e) { if (MISSING CODE == 112)

You type e.KeyCode and you press Enter.

You have accessed the property from the KeyEventArgs object that identifies what key has been released.

using System.Drawing.Color;public class frmMouseKeyBoardEvents : System.Windows.Forms.Form{ private void frmMouseKeyBoardEvents_KeyUp(object

Page 119: 1_Windows Forms Creation With C# 2005

sender, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode == 112)

Now you want to include the code that makes the lblHelpMessage label visible when the user releases the F1 key – ASCII code 112 – and invisible when the ESC key – ASCII code 27 – is released. You continue to use the KeyCode property to determine which key the user has released and then provide the appropriate response to the user action.

{ lblHelpMessage.Visible = true; } else if (e.KeyCode == 27) { lblHelpMessage.Visible = false; } }}

Suppose you've created an event handler for a button control – Button1 – on a form. The event handler

handles the button's Click event, which makes the list box – Listbox1 – visible when the button is

clicked.

You've now added a menustrip – MenuStrip1 – to the form, which contains a single menu item –

MenuItemList – that produces the same result as clicking the button.

public class Form1

You change the button's event handler so that it displays ListBox1 when either Button1 or

MenuItemList is clicked.

using System.Drawing.Color;

public class Form1{ private void Button1_Click(object sender, System.EventArgs e) { ListBox1.Visible = true; }

}

Page 120: 1_Windows Forms Creation With C# 2005

Say you want to create a dynamic event handler to handle a button control's click event at runtime. When the button is clicked, text from the Textbox1 control is displayed in Label2.

public class Form1

To do this, you create a method signature for the event handler Button1_Click and you include the

event handler code, which in this case is simply assigning the text entered from the text box control to the label control.

private void Button1_Click(object sender, System.EventArgs e) {

Label2.Text = TextBox1.Text; }

Now you want to specify, within the form's Load event, the handler that will be handling the button

control's Click event.

public class Form1{ private void Button1_Click(object sender, System.EventArgs e) {

Label2.Text = TextBox1.Text; } private void Form1_Load(object sender, System.EventArgs e) { MISSING CODE new System.EventHandler(Button1_Click); }}

To specify the event handler you type Button1.Click += and you press Enter.

You've created a dynamic event handler.

public class Form1{ private void Button1_Click(object sender, System.EventArgs e) {

Label2.Text = TextBox1.Text; } private void Form1_Load(object sender, System.EventArgs e) {

Page 121: 1_Windows Forms Creation With C# 2005

Button1.Click += new System.EventHandler(Button1_Click); }}

Question

You've created the btnShow_Click event handler to respond to the btnShow

button's Click event only at runtime. In the += statement, you now need to

specify the event handler that will handle the Click event.

Complete the code to specify which event handler should handle the event.

public class Form1{ private void btnShow_Click(object sender, System.EventArgs e) {

Label1.Visible = true; } private void Form1_Load(object sender, System.EventArgs e) { btnShow.Click += MISSING CODE( btnShow_Click); }}

Answer

To complete the code you type new System.EventHandler.

Question

Suppose you've created an event handler, btnChange_Click, that handles the

Click event for the btnChange button control. You've also included the

rdChange radiobutton control to provide the same functionality as the button

control when the control is clicked, firing its own Click event.

Which code do you include to handle both events with the single event handler method, but seperate EventHandler delegates?

Page 122: 1_Windows Forms Creation With C# 2005

public class Form1{ private void initHandlers(object sender, System.EventArgs e) { MISSING CODE }

}

Options:

1.btnChange.Click += new System.EventHandler(btnChange_Click);btnChange.Click += new System.EventHandler(btnChange_Click);

2.btnChange_Click += new System.EventHandler(rdChange);btnChange_Click += new System.EventHandler(btnChange);

3.btnChange.Click += new System.EventHandler(btnChange_Click);rdChange.Click += new System.EventHandler(btnChange_Click);

Answer

To handle both events with the radio control's event handler you include the code

btnChange.Click += new System.EventHandler(btnChange_Click);rdChange.Click += new System.EventHandler(btnChange_Click);

Option 1 is incorrect. This adds the event handler method twice to the same control. The Click event of the rdChange control has not been addressed.

Option 2 is incorrect. Here the method name is being used to specify delegates where the control has been passed as a parameter. The control's event name is used to specify delegates where the method name is passed in as a parameter.

Option 3 is correct. You specify each even of a given control, then use the += operator along with Event Handler delegates to associate an event with your new event handler method.

3. Recognizing Windows Forms modifier keys

Page 123: 1_Windows Forms Creation With C# 2005

Modifier keys are the Shift, Alt, and Ctrl keys found on a keyboard. You can program your application to respond appropriately to modifier keys, especially when they are used in combination with primary keys – such as pressing Shift+r to form a capital R or pressing Ctrl+Z to undo an action.

You can use an event handler to determine whether a particular modifier key has been pressed. There are two methods of determining this, depending on which keyboard event is being handled. You can choose to test for modifier keys when either one of these keyboard events occur:

KeyDown

KeyPress

KeyDown

When handling the KeyDown event, you can use the Modifiers or KeyData properties

of the KeyEventArgs class to determine which modifier key has been pressed. The

Modifiers property specifies which modifier key has been pressed. The KeyData

property specifies the character that was pressed and any modifier key that it was combined with. You can also use the KeyCode property of the KeyEventArgs class to

determine which modifier key has been pressed. This property gets the keyboard code for the KeyDown event. If a modifier key is pressed together with another key, the two keys

form a combined key code value that is passed to the KeyCode property.

KeyPress

When handling the KeyPress event, you need to use the ModifierKeys property of the

Control class to determine which modifier key has been pressed. This event takes in an

instance of KeyPressEventArgs as a parameter, specifying the pressed key through its

KeyChar property.

Whether you are handling a KeyPress or KeyDown event you need to use the Keys enumeration when

testing for modifier keys within an event handler. The Keys enumeration contains a list of all keyboard

keys and provides every variation of each modifier key. For example, the Shift modifier key has the variations ShiftKey, RShiftKey, and LShiftKey.

Question

Which property can you use when checking for modifier keys with the KeyPress

event?

Options:

1. KeyCode

2. Modifiers

3. ModifierKeys

Answer

Page 124: 1_Windows Forms Creation With C# 2005

You can use the ModifierKeys property to check for modifier keys with the

KeyPress event.

Option 1 is incorrect. The KeyCode property is available in the KeyEventArgs

class, which can be used when testing for modifier keys when the KeyDown or

KeyUp events are being handled. It is not available to the KeyPress event.

Option 2 is incorrect. The Modifiers property is only available to the

KeyEventArgs class, which cannot be used with a KeyPress event.

Option 3 is correct. You use the ModifierKeys property of the Control class to

check for modifier keys when the KeyPress event is being handled.

Suppose you create an event handler for a form's KeyDown event and you want to check which modifier

key – Shift, Ctrl, or Alt – a user presses in combination with the "A" character on the keyboard.

public class frmModifierKeys

First you define the event handler to handle the KeyDown event. In this case it is

frmModifierKeys_KeyDown. An object of the KeyEventArgs parameter is passed to the event

handler, which enables you to access the KeyCode property of the KeyDown event.

{ private void frmModifierKeys_KeyDown(object sender,System.Windows.Forms.KeyEventArgs e) {

You first want to test whether the user has pressed the Shift key with the "A" key. So you need to get the keyboard code for the KeyDown event.

public class frmModifierKeys{

private void frmModifierKeys_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if (MISSING CODE == Keys.A & (e.Shift & ! e.Control & ! e.Alt)) { MessageBox.Show("Pressed: SHIFT + A"); }

To get the keyboard code for the KeyDown event, you type e.KeyCode and you press Enter.

Page 125: 1_Windows Forms Creation With C# 2005

The keyboard code for the KeyDown event is contained in the KeyCode property. In this case, you

compare the contents of the KeyCode property with the result of a bitwise & operation between Keys.A

and a conditional statement that determines which modifier key was pressed.

public class frmModifierKeys{ private void frmModifierKeys_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode == Keys.A & (e.Shift & ! e.Control & ! e.Alt)) { MessageBox.Show("Pressed: SHIFT + A"); }

And you create similar conditional statements that test for each modifier key.

if (e.KeyCode == Keys.A & (! e.Shift & e.Control & ! e.Alt)) { MessageBox.Show("Pressed: CONTROL + A"); } if (e.KeyCode == Keys.A & (! e.Shift & ! e.Control & e.Alt)) { MessageBox.Show("Pressed: ALT + A"); } }}

Question

Suppose you've created an event handler that handles the KeyDown event and

checks whether a user has pressed the Ctrl key with the S key on a keyboard to save information in an application. You need to get the combined keyboard code for the KeyDown event.

Complete the code to do this.

public class frmModifierKeys { private void frmModifierKeys_KeyDown(object sender,System.Windows.Forms.KeyEventArgs e) { if (e. MISSING CODE== Keys.S & e.Control) {

Page 126: 1_Windows Forms Creation With C# 2005

MessageBox.Show("Data Saved"); } }}

Answer

To complete the code to receive the combined keyboard code for the KeyDown

event, you type KeyCode.

4. Overriding base methods in Windows Forms

When creating Windows Forms applications you often create your own base classes containing their own methods and events. You may want to use a method from the base class in a child class but include some additional functionality in the method.

Instead of creating a new method to use within the child class, you can override the default method of the derived base class.

When you want to override a method in the child class, you use the override keyword together with the

name of the method to specify that the method must be overridden.

[public,private,...] override void method()

{ code to execute}

In the parent class you can specify that a method must be overridden using one of the following keywords:

abstract

virtual

abstract

You use the abstract keyword to specify that a method is defined but not implemented

in the base class and must be overridden in the child class before it can be used.

Description of the syntax for the MustOverride keyword follows:

[public,private,...] abstract void method()

{

code to execute

}

Page 127: 1_Windows Forms Creation With C# 2005

Description ends

virtual

You use the virtual keyword to specify that a usable method defined in the base class

can be overridden in the child class.

Description of the syntax for the Overridable keyword follows:

[public,private,...] virtual void method()

{

code to execute

}

Description ends

Suppose the base class, clsPerson, contains a show method. You want to use the show method in the

child class, clsStudent, but with different functionality.

public class clsPerson

First you need to indicate in the clsPerson class that the show method can be overridden by a child

class. You do so using the virtual keyword.

public string strName;

public virtual void show() { MessageBox.Show("Show() method in clsPerson Class"); }

}

The show method in the clsStudent class now overrides the show method in the clsPerson class.

Note that the child class inherits clsPerson in order to have access to the original show method. The

code within this method in the child class will now run in the place of the code that had been defined in the parent class. Had this not been done, calling show on the child object would have invoked the method

in the parent class.

public class clsStudent : clsPerson{

public MISSING CODE void show()

Page 128: 1_Windows Forms Creation With C# 2005

{ MessageBox.Show("name is " + strName); }

}

You type override and you press Enter.

The show method in the clsStudent class overrides the show method in the clsPerson class.

public class clsStudent : clsPerson{

public override void show() { MessageBox.Show("name is " + strName); }

}

Question

Say you've declared a method, price() in the base class – clsFurniture –

that has a specific functionality, but you want to use this method, with additional functionality, within a child class. You need to specify in the base class that the method can be overridden in the child class.

Type the code to do this.

public class clsFurniture{ public string strName;

public MISSING CODE void price() { MessageBox.Show("Price() method in clsFurniture Class"); }

}

Answer

Page 129: 1_Windows Forms Creation With C# 2005

To specify that the method can be overridden in the child class, you type virtual.

Summary

Event handlers are methods that provide code in response to events, such as a user clicking a button on a form.

You can create event handlers to handle keyboard events, such as the KeyDown and KeyPress events.

Event handlers can also respond to mouse events, such as the MouseUp and Click events. Dynamic

event handlers can also be created to respond to events raised by dynamic controls. When several controls on a form provide the same functionality, you can create a single event handler to respond to multiple events.

Modifier keys are special keys – such as Ctrl, Shift, and Alt – that are found on a keyboard. You can create event handlers to handle these special keys.

You may want to use methods defined in a base class within a child class but with added functionality. To do this, you can override the method in the child class so that the functionality of the original method in the base class is not lost.

Creating Event Handlers and Overriding a Base Method

Learning objective

After completing this topic, you should be able to create a runtime event handler, connect multiple events to a single event handler, and override a base method in a Windows Forms application.

Exercise overview

In this exercise, you're required to create event handlers and override a base method in a Windows Forms application.

This involves the following tasks:

creating an event handler at runtime

connecting multiple events to a single event handler

overriding a base method

Task 1: Creating an event handler at runtime

Page 130: 1_Windows Forms Creation With C# 2005

You have a Windows Forms application with a radio button control. You want to create an event handler to handle the CheckedChanged event for the radio button control at runtime.

Step 1 of 2

You need to define the method signature for a dynamic event handler, which is to handle the rdNotify button control's CheckedChanged event at runtime.

Which code correctly defines the method signature for the dynamic event handler?

private void rdNotify_CheckedChanged MISSING CODE { txtUserEmail.Enabled = true; }

Options:

1. (System.Object sender)

2. (System.EventArgs sender, System.Object e)

3. (System.Object sender, System.EventArgs e)

Result

The code that correctly defines the method signature for the dynamic event handler is(System.Object sender, System.EventArgs e)

Option 1 is incorrect. An event handler requires two parameters to correctly handle an event. In this case, you need to include the parameter – e – of the

System.EventArgs type, which contains event data.

Option 2 is incorrect. As the first parameter in its method signature, an event handler accepts an object of type System.Object, not System.EventArgs. The

System.EventArgs parameter is the second parameter and provides event data

to the event handler.

Option 3 is correct. The event handler's method signature accepts an object of type System.Object as its first parameter, and an object of type

System.EventArgs as its second parameter.

Step 2 of 2

Page 131: 1_Windows Forms Creation With C# 2005

You've created the method signature for the rdNotify_CheckedChanged

dynamic event handler and now you want to specify, within the form's Load event,

the handler that will be handling the CheckedChanged event for the rdNotify

button control.

Type the code to do this.

public class Form1{ private void rdNotify_CheckedChanged(object sender, System.EventArgs e) { txtUserEmail.Enabled = true; } private void Form1_Load(object sender, System.EventArgs e) {

rdNotify.CheckedChanged += MISSING CODE(rdNotify_CheckedChanged); }}

Result

You type new System.EventHandler to specify the handler that will be

handling the CheckChanged event for the rdNotify button.

Task 2: Connecting multiple events to a single event handler

Currently, to open a file in your Windows Forms application, a user needs to navigate to the Open menu item. You want to simplify navigation for the user by including a button – btnOpen – that provides the same functionality when it is clicked.

Step 1 of 1

You want to change the mnuOpen_Click event handler into a multiple event

handler so that it handles the Click event for both the mnuOpen and btnOpen

controls.

Complete the code to do this.

Page 132: 1_Windows Forms Creation With C# 2005

public class Form1{MISSING CODE += new System.EventHandler(mnuOpen_Click);

private void mnuOpen_Click(object sender, System.EventArgs e) {

OpenFileDialog1.ShowDialog(); }}

Result

To complete the code that causes the event handler to handle multiple events, you type btnOpen.Click

Task 3: Overriding a base method

Suppose you have a base class – clsDepartment – in your Windows Forms application and this class

has the showrating() method that displays a rating for a department based on a score earned.

Step 1 of 2

You want to specify that the showrating() method, defined in the

clsDepartment base class, can be overridden when used in a child class.

What code do you use to specify this?

public class clsDepartment{

public int intScore; public int intRating;

public MISSING CODE void showrating() { MessageBox.Show("showrating() method in clsDepartment Class"); }}

Options:

Page 133: 1_Windows Forms Creation With C# 2005

1. abstract

2. virtual

3. override

Result

The code you use to specify that it is possible, but not required, for a method to be overridden by a child class isvirtual.

Option 1 is incorrect. You use the abstract

keyword to specify that the showrating() method must be overridden by a child

class before it can be used in the child class.

Option 2 is correct. In this case, you use the virtual keyword if you want to

specify that it is possible for the showrating() method to be overridden by a

child class.

Option 3 is incorrect. You use the override keyword when you want to specify,

within the child class, that the method is being overridden.

Step 2 of 2

You want to use the showrating method in the clsFinance child class, which it

inherits from the clsDepartment base class. You want to override the base

class's showrating method in the child class.

Type the code to do this.

public class clsFinance : clsDepartment{

public MISSING CODE void showrating() { MessageBox.Show("Rating for finance department is:" + intRating); }

}

Result

Page 134: 1_Windows Forms Creation With C# 2005

The code you use to override the showrating method in the child class is

override.

A dynamic event handler and an event handler to handle multiple events have been created, and a base class method has been overridden.


Recommended