Print | Contents | Close |

Windows Forms in Visual Studio 2005

Learning objective

After completing this topic, you should be able to identify various Windows Forms enhancements in Visual Studio 2005.

1. Windows Forms controls

Visual Studio 2005 provides new Windows Forms controls that simplify form design and extend the functionality of forms.

You can upgrade C# 1.0 or 1.1 projects to C# 2.0 (C# 2005) using the new Upgrade Wizard.

The Upgrade Wizard upgrades some ActiveX controls in the Windows Common Controls Library to Windows Forms controls. However, the differences in functionality between the ActiveX controls and the Windows Forms controls are minimal.

To upgrade Microsoft HTML Object Library controls, however, you use the new managed HTML Document Object Model.

Note

Using the Upgrade Wizard, you can also upgrade the coding language features of an application. For example, the wizard upgrades certain old code to C# 2.0.

To add a Windows Forms control to a form, you first open the Toolbox by selecting View - Toolbox. You can then select a control in the Toolbox and drag it onto the form, or double-click a control to add it to a default position on the form.

Most Windows Forms controls have associated Tasks menus, which enable you to customize the controls. You access the Tasks menu for a control by clicking the control on the form and then clicking the arrow that displays in the control's top right corner.

Several new types of controls in Visual Studio 2005 that simplify form design and enhance form functionality include

Strip controls
The old toolbar types of controls have been replaced with "strip" controls in Visual Studio 2005. Strips have similar functionality and appearance to those found in Windows XP, Office, and Internet Explorer. You can customize them to contain any other controls, such as those for data management.

You access strip controls in the Menus & Toolbars section – or in the Common Controls or All Windows Forms sections – of the Toolbox.

Examples of strip controls included in the Toolbox are ContextMenuStrip, MenuStrip, StatusStrip, ToolStrip, and ToolStripContainer.

Each strip control has an associated Tasks menu.

The MenuStrip Tasks menu, for example, enables you to add the MenuStrip control to the ToolStripContainer control, to insert standard items, and to configure rendering, docking, and the display of grips for the control. Clicking the Edit Items link opens the Items Collection Editor, which you can use to add or remove MenuStrip components.

The MenuStrip Tasks menu includes Embed in ToolStripContainer and Insert Standard Items links, RenderMode, Dock, and GripStyle drop-down list boxes, and an Edit Items link.

The StatusStrip control provides a drop-down list of control types that you can embed in it.

The items you can add to the StatusStrip control using the drop-down list are StatusLabel, ProgressBar, DropDownButton, and SplitButton.

The ToolStrip control provides a drop-down list of controls that you can add to it. Alternatively, you can add controls to it using the Insert Standard Items link in the Tasks menu for the control.

The controls you can add to the ToolStrip control using the drop-down list include Button, Label, SplitButton, DropDownButton, Separator, ComboBox, TextBox, and ProgressBar.

You can position the MenuStrip, StatusStrip, and ToolStrip controls at any place on a form by embedding them in the ToolStripContainer, and then using the Tasks menu for ToolStripContainer to specify where panels must display.

The ToolStripContainer Tasks menu includes a Panel Visibility section with Top, Bottom, Left, and Right checkboxes, as well as a Re-parent Controls link.
Layout controls
Visual Studio 2005 introduces layout controls that enable flexible positioning and configuration.

You find the layout controls in the Containers section of the Toolbox.

Examples of layout controls listed in the Toolbox include FlowLayoutPanel and TableLayoutPanel.

The TableLayoutPanel control lets you create panels that resize easily, using new ColumnSpan and RowSpan properties, which mimic those of HTML table cells.

The Tasks menu for the TableLayoutPanel control includes Add Column, Add Row, Remove Last Column, Remove Last Row, and Edit Rows and Columns links.

The FlowLayoutPanel control allows form content to flow freely as it resizes.

On a form, the control is enclosed by a dotted line and includes anchors for resizing it.
View controls
Examples of enhanced view controls in Visual Studio 2005 include TreeView and ListView.

The new TreeView control has a collection of child nodes reserved for every node that it contains.

You can now also add child nodes directly to a parent node using the TreeNode Editor, which you open by clicking the Edit Nodes link.

The TreeView Tasks menu includes an Edit Nodes link, an ImageList drop-down list box, and a Dock in parent container link.

The old ActiveX control for creating tree views in earlier versions of Visual Studio had a single node collection.

The TreeNode Editor enables you to add a root to the tree, to edit nodes, and to view the properties of nodes.

The TreeNode Editor has two text boxes – one labeled Select a node to edit, and the other labeled Properties. There is an Add Root button, which is active by default, and an Add Child button which becomes active when a root is present.

The ListView control now provides a tile view, which displays tiles with icons and text. It also lets you group items into related categories.

A new insertion mark feature displays feedback and shows drop locations when users drag and drop items.

The ListView Tasks menu includes Edit Items, Edit Columns, and Edit Groups links, three drop-down list boxes – View, Large ImageList, and Small ImageList, and a Dock in parent container link.

You can select an ImageList control to display in a ListView control. The ImageList control lets you select the image size and bit depth that images will display in, and to select images.

The ImageList Tasks menu has drop-down list boxes for selecting image size and image bit depth, as well as a Choose images link.
Data-handling controls
Visual Studio 2005 offers improved data-handling controls including the BindingNavigator, BindingSource, and DataGridView controls.

The BindingNavigator control belongs to the ToolStrip class, and has buttons for adding, deleting, and navigating data records.

The BindingNavigator Tasks menu has three links – Embed in ToolStripContainer, Insert Standard Items, and Edit Items. It also includes RenderMode, Dock, and GripStyle drop-down list boxes.

The BindingSource control is a back-end control that binds controls on a form to data sources such as Access or SQL databases. You use and manipulate the control programmatically.

The DataGridView control displays data in a table. It can show read-only previews of small amounts of data, or large writeable datasets. It can be bound to external source data, or you can add data to it directly.

The DataGridView control is similar to the DataGrid control, but doesn't require that you write your own code. It also supports bound or unbound columns.

The DataGridView Tasks menu includes a Choose Data Source drop-down list box, Edit Columns and Add Columns links, and four checkboxes – Enable Adding, Enable Editing, Enable Deleting, and Enable Column Reordering. It also includes a Dock in parent container link.

The PropertyGrid control lets you customize the settings that users can change in an application. You can add customized and expandable property lists. The PropertyGrid control does not have an associated Tasks menu – you customize it using code and its properties.
Text box controls
Visual Studio 2005 provides the RichTextBox and MaskedTextBox controls.

The RichTextBox control makes text entry, display, and formatting easier. To place text in the control, you can enter it directly, or load it in rich (.rtf) or plain (.txt) text format.

File management features include LoadFile and SaveFile. Find lets you search for text characters or strings. URL links can be displayed correctly using DetectURLs.

The RichTextBox Tasks menu includes Edit Text Lines and Dock in parent container links.

The MaskedTextBox control provides enhanced mask characters. Clicking the Set mask link in the control's Tasks menu opens the Input Mask dialog box.

Set Mask is the only option in the MaskedTextBox Tasks menu.

The Input Mask dialog box enables you to select a predefined input mask or to define a custom mask.

The Input Mask dialog box includes a pane that lists details of available masks in Mask Description, Data Format, and Validating Type columns. It also includes Mask and Preview text boxes, and a Use Validating Type checkbox.
Port, sound, and browser controls
The SerialPort control, which uses the new SerialPort class, enables serial devices such as modems to communicate with an application.

This control replaces MSComm, and increases digital access to the .NET environment. It is a back-end control without a visual interface.

The SoundPlayer control enables you to obtain or specify the file path or URL of a .wav file to load. You attach the code for the soundplayer to an object on the form because it doesn't have a visual interface.

The WebBrowser control enables you to incorporate a web browser in a form. The control exposes more application programming interface (API) members than previous versions of C#, and introduces support for client-side scripts.

You can configure a web browser using the properties of the WebBrowser control. Examples of these properties include

To enable or disable a web browser's context menu, you use the IsWebBrowserContextMenuEnabled property. This property is set to True by default.

To enable or disable the browser's keyboard shortcuts, you use the WebBrowserShortcutsEnabled property. This property is set to True by default.

You allow or prevent users from navigating away from a page using the AllowNavigation property, which is set to True by default.

You prevent users from dropping files or URLs onto the browser by setting the AllowWebBrowserDrop property to False. Its default value is True.

You set a control to navigate to an address using the Url property and the Navigate method. The Url property isn't set to a default value.

Question

What does the PropertyGrid control enable you to do?

Options:

  1. Change the Application Framework properties for an application
  2. Change the properties of controls on a form
  3. Set the properties of grids that display data
  4. Specify which settings a user can change in an application

Answer

The PropertyGrid control enables you to specify which settings a user can change in an application.

Option 1 is incorrect. The Application Property tabbed page provides access to the Application Framework properties for an application.

Option 2 is incorrect. Every control has its own properties, which you access by right-clicking the control and selecting Properties.

Option 3 is incorrect. The DataGridView control properties enable you to change how data is displayed in an application.

Option 4 is correct. The PropertyGrid control provides customizable and expandable property lists that enable users to change application settings.

Question

What can you do using the WebBrowser control?

Options:

  1. Enable users to change web browser settings
  2. Configure a control to enable navigation to a specific location
  3. Create more API members
  4. Prevent users from navigating away from a page

Answer

The WebBrowser control enables you to configure a control to navigate to a specific location, and to prevent users from navigating away from a page.

Option 1 is incorrect. The user only sees the result of your actions with WebBrowser, which integrates Internet Explorer into applications.

Option 2 is correct. You can configure a control to navigate to an address using the Url property and the Navigate method.

Option 3 is incorrect. The WebBrowser control provides greater access to API members than previous versions of Visual Studio, but it does not create them.

Option 4 is correct. You can prevent a user navigating away from a page using the AllowNavigation property, which employs the Navigating and Navigated event handlers.

2. The BackgroundWorker control

The BackgroundWorker control is from a new class that overcomes slow interface responses by executing operations asynchronously, on a thread other than the one your program uses.

BackgroundWorker is a class for back-end control – there is no direct visual link to it, so it must be used programmatically.

Note

When you write code in Visual Studio 2005, IntelliSense provides numerous pop-up windows that provide for the optional insertion of end constructs.

You can disable this feature by modifying Visual Studio 2005 settings.

There are three main components to BackgroundWorker. First you declare and create a variable to serve as an instance of the BackgroundWorker control.

Then you create the methods which cause the process to run on a background thread, as well as the code for the process itself.

Finally, you provide the code that causes the process to be executed by BackgroundWorker.

To code BackgroundWorker, you first declare and instantiate a variable in the subroutine for the form Load event. This example does not use IntelliSense code completion.


using System.ComponentModel;
public class Form1
{
private BackgroundWorker worker;
private void Form1_Load(object sender, System.EventArgs e)
{
worker = new BackgroundWorker();

You then enable the WorkerReportsProgress property by assigning it the value of True. This causes the BackgroundWorker to report its progress.

    worker.WorkerReportsProgress = True;

You add the event handler that will trigger when the DoWork event of BackgroundProcess occurs. This event will occur when methods class methods such as RunWorkerAsync run. In this example, the user-defined OnWork method is passed to the handler so it will execute when the handler is triggered.


using System.ComponentModel;
public class Form1
{
private BackgroundWorker worker;
private void Form1_Load(object sender, System.EventArgs e)
{
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += new DoWorkEventHandler(OnWork);

You then add the event handler for the ProcessChanged event, which is raised by the class's ReportProgress method. This event is intended to check the progress of the background progress and in this case, the user-defined OnProgressChanged method is passed to the handler for execution. This will conclude the Form_Load event.


worker.ProgressChanged += new ProgressChangedEventHandler(OnProgressChanged);

Next you define the subroutine for the OnWork method. In this subroutine, you create the process that you want to run on a background thread.


}
}

private void OnWork(object sender, DoWorkEventArgs e)
{
int I;
for (I = 1; I <= 100; I++) {
System.Threading.Thread.Sleep(10);
worker.ReportProgress(I);
}
}

You define the OnProcessChanged method. This will run the Invoke method, passing a new handler for a progress bar and will run its own customized method for that handler, all designed to display the percentage of the progress that has been completed.

Finally, you directly define the handler for a form button's (button1) click event. This event will run the RunWorkerAsync method to begin the entire example.

Question

Suppose you need to use the BackgroundWorker class to run a background process when the user clicks a button.

Complete the code that adds the handler that begins the process for a BackgroundWorker to an object named worker.



MISSING CODE += new DoWorkEventHandler(OnWork);

Answer

You complete the code that adds the DoWork handler to the worker object by typing

worker.DoWork

Question

You've declared and instantiated the variable worker as an instance of BackgroundWorker.

Complete the code that causes BackgroundWorker to run when the user clicks a button.



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

Answer

The code that causes BackgroundWorker to run when the user clicks a button is

worker.RunWorkerAsync()

Visual Studio 2005 lets you configure Application Framework settings using the Application pane of the properties window for an application.

You can enable or disable Windows XP visual styles, using the Enable XP visual styles checkbox.

You can specify whether the application is single-instance by selecting the Make single instance application checkbox. This is possible because Visual Studio uses the new MyProject namespace.

You can determine whether an application's settings are saved when it closes, by selecting the Save My.Settings on Shutdown checkbox.

You can determine the application's authentication mode – Windows or Application-Defined – using the Authentication mode drop-down list box. You can also set the event that triggers application shutdown, and configure the application's splash screen.

The Debug properties pane now enables you to activate a new hosting process. You do this by selecting the new Enable the Visual Studio hosting process checkbox.

Question

Which of these options are treated as Application Framework settings?

Options:

  1. Determining the application's authentication mode
  2. Enabling XP visual styles
  3. Specifying how devices can communicate with your application.
  4. Specifying which coding language features are upgraded

Answer

Determining the application's authentication mode and enabling XP visual styles are Application Framework settings.

Option 1 is correct. The Application Framework settings determine how an application functions once it is compiled.

Option 2 is correct. The Application Framework settings enable you to customize the application interfaces.

Option 3 is incorrect. The SerialPort control determines how devices can communicate with your application.

Option 4 is incorrect. The Upgrade Wizard automatically upgrades any coding language features that can be upgraded.

Summary

Visual Studio 2005 includes several new Windows Forms controls that simplify and enhance form design. You access these controls in the Visual Studio Toolbox.

The new BackgroundWorker control makes it easy to assign processes to background threads. The Application pane of the properties window now lets you configure Application Framework settings directly.