This documentation is archived and is not being maintained.

Chapter 5: Constructing User Interfaces

Visual Studio 2005
 

Microsoft Corporation

March 2006

Summary: New controls and improvements in the Microsoft .NET Framework 2.0 allow you to create professional-looking applications that provide a better end-user experience and reduce your coding effort. (13 printed pages)

Contents

Application: New Windows Forms Controls
Application: Changes to Existing Windows Forms Controls

Application: New Windows Forms Controls

This application demonstrates many of the new controls available in Microsoft Visual Studio 2005 for creating compelling Windows Forms user interfaces.

New Concepts

Visual Studio has a long history of providing a large library of prebuilt controls that allow developers to quickly create user interfaces for Microsoft Windows applications. However, the capabilities and visual style of these components often resulted in applications that had a look and feel significantly different from other Microsoft products such as Microsoft Office and Internet Explorer. Visual Studio 2005 introduces many new controls to address this issue. These controls provide the same advanced look and feel and customization support as Microsoft Office, which allows you to provide your users with a familiar experience and increased personalization options.

ToolStrip Control

Today's professional applications provide many features that allow users to fully customize the positioning, formatting, and content of their menus and toolbars. Users expect to be able to perform such tasks as moving toolbars around, selecting which buttons to display, and controlling how much information is presented with each item. In addition, they expect the rendering of these controls to be clean and consistent across applications. The ToolStrip is a new toolbar control that supports all these features and also provides the base functionality for the MenuStrip and StatusStrip controls. You are no longer limited to just adding buttons to your toolbars. The ToolStrip allows you to add seven different types of items, such as the ToolStripButton, ToolStripComboBox, ToolStripTextBox, and ToolStripSplitButton.

Aa730862.netvbdev0501(en-US,VS.80).gif

Figure 1. Professional looking application using new strip controls.

The first thing you will notice when you add a ToolStrip to a form is that it looks like an Office toolbar by default. Many controls support a new pluggable rendering framework that allows you to select how you want the control to look. There are currently two main "looks" for the ToolStrip, and you select which one you want with the RenderMode property. Providing a value of System indicates that you want the control to follow the current Windows system display settings. Providing a value of Professional indicates that you want the control to look like its counterpart in Microsoft Office.

There are many new types of behavior—including rafting, merging, and item overflow—supported by the ToolStrip. Rafting is the behavior that allows a user to drag and drop a toolbar to various locations on the form and have the toolbar automatically "snap" into position. The strip controls also support rafting. By placing the controls in a ToolStripContainer control, you can allow the user to position the toolbars as desired, including moving multiple toolbars to the same horizontal line.

Merging is the behavior you see when the items from a child MDI ToolStrips are combined into the parent form's ToolStrip. You can specify whether or not a particular strip supports merging with the AllowMerge property.

Item reordering is the behavior that allows a user to rearrange toolbar and menu items. You can enable item reordering by setting the AllowItemReorder property to True. At run time, users will be able to move items by dragging and dropping them while pressing the Alt key.

FlowLayoutPanel and TableLayoutPanel Controls

Visual Studio 2005 provides two new layout controls that address some common control positioning scenarios. The normal Panel control uses absolute positioning to determine the location of each of its child controls. The FlowLayoutPanel, on the other hand, positions each control relative to the one just prior to it as you add them to the panel. By default, it flows controls from left to right and top to bottom, but you can control the flow direction by using the FlowDirection property. The FlowLayoutPanel is useful in situations where you want controls to automatically reposition themselves as the contents of one of the children changes or as the size of the panel changes.

The TableLayoutPanel is a panel that contains an invisible table structure that allows you to place a single control in each table cell. You can specify how many rows and columns the internal table should have as well as the sizing rules for each row and column. The TableLayoutPanel is useful when you need to define major, fixed-size sections of a form. You can also use it to quickly create tabular data-entry interfaces. However, keep in mind that you can add only a single control to each cell. So, if you want a cell to contain more that one child control, you need to first add a Panel to the cell and then add your two child controls to the Panel.

WebBrowser Control

Visual Studio 2005 now provides an optimized, managed wrapper for the wel1-known ActiveX Web browser control. This control provides access to the full DHTML rendering capabilities of Internet Explorer. You can use this control to add many kinds of Web browsing capabilities to your applications. For example, you could allow users to read HTML documentation files from within your application. Or you could allow a user to link to content on the Internet. Using the WebBrowser control is straightforward, and it provides some powerful options that enable deep integration between your DHTML and WinForm assets.

You can download and display a document by simply calling the Navigate method and providing a URL to the resource. Once it's loaded, you can programmatically access the DHTML DOM through the Document property. Through this property, you can directly read and modify the structure of the document. You can perform standard navigation tasks through methods such as GoForward, GoHome, GoSearch, and GoBack. You can even expose a managed object to script code to allow script in the page to call into your managed application. All you have to do is supply an object to the ObjectForScripting property. Monitoring the progress of a download is accomplished by handling the WebBrowser's events, such as Navigating, Navigated, ProgressChanged, and DocumentCompleted.

Walkthrough

This walkthrough demonstrates how you can use these new controls to create Windows Forms interfaces that look more professional and are easier to use.

Creating Office Interfaces

The DocumentBrowser form presents an interface that draws many of its design elements from various Microsoft products, including Office and Internet Explorer. Notice that the two ToolStrips are rendered as Office-type toolbars, with a vertical gradient background and "grips" at their left edge. One of the ToolStrips includes a text box. There is also a third ToolStrip control in the bottom-left corner of the form with two items, Documents and Web Pages. This ToolStrip has been modified by setting its LayoutStyle to Vertical to give it a bit of a Microsoft Outlook style. The status bar at the bottom of the form is a StatusStrip control with two children, a ToolStripStatusLabel and a ToolStripProgressBar. The progress bar has been configured to display progress as a continuous strip by setting its Style property to Continuous.

When you run the application, click and drag the tool strips to any edge of the form and you will see that they will automatically dock to that side. This action is possible because there is a ToolStripContainer that fills the form. This container can be optionally added by Visual Studio when you add the ToolStrips to the form. You can also reorder items and even move an item from one ToolStrip to another by holding down the Alt key and dragging an item.

Interacting with Web Content

The application uses the WebBrowser control to load and display Web content. At run time, click the Web Pages button in the bottom-left corner of the form. Next, enter a URL into the Address text box in the tool strip. Click the Go button to navigate to the document.

As the application loads, you should notice the progress bar and status text updating at the bottom of the form. This progress monitoring is accomplished by handling WebBrowser control events.

Aa730862.netvbdev0502(en-US,VS.80).gif

Figure 2. Document browser application

The process starts with the GoToolStripButton_Click event handler. In this procedure, you tell the WebBrowser to load a document by calling the Navigate method:

MainWebBrowser.Navigate(AddressToolStripTextBox.Text)

When the WebBrowser starts navigating to the resource, it raises the Navigating event. The wbrBrowser_Navigating event handler retrieves the URL from the event arguments and posts a message to the StatusStripPanel indicating that the download is in progress:

InfoToolStripStatusLabel.Text = "Opening " & e.Url.ToString()
DocToolStripProgressBar.Visible = True
DocToolStripProgressBar.Value = 0

While the WebBrowser is loading the document, it periodically raises its ProgressChanged event. The MainWebBrowser_ProgressChanged event handler updates the progress bar in the StatusStrip:

        With DocToolStripProgressBar
            .Value = e.CurrentProgress
            .Maximum = e.MaximumProgress
        End With

When the WebBrowser is finished loading the document, it raises the DocumentCompleted event. You can use this event to notify your user that the content is available or perhaps to log the results of the download:

InfoToolStripStatusLabel.Text = "Done"
DocToolStripProgressBar.Visible = False

Interacting with Document Content

The application also allows you to load and display files that have been registered to allow OLE hosting. Office documents, sound files, and .avi movie files are all examples of "active" data. You can load a file by first selecting the Documents button in the bottom-left corner of the form. Then, enter a local path to the desired file in the Address text box and click the Go button. You will notice that when the Documents button is selected, the auto-complete for the Address text box shows files instead of web URLs. The document will display inside the WebBrowser.

Aa730862.netvbdev0503(en-US,VS.80).gif

Figure 3. Displaying documents

Conclusion

The new Windows Forms controls provided by the .NET Framework 2.0 allow you to create applications that are more professional looking and more powerful than ever before without having to rely on third-party components. The ToolStrip provides you with a powerful mechanism for creating menus, tools, and status bars that look and behave like their counterparts in other applications your users are familiar with. This can translate directly into quicker user adoption and higher user satisfaction. The WebBrowser allows you to integrate external data into your applications. The WebBrowser is designed for the reliable and versatile downloading and rendering of DHTML content, and provides a mechanism for hosting and editing OLE data types.

Application: Changes to Existing Windows Forms Controls

This application examines some changes and additions to the Windows Forms framework that affect a broad set of existing and new Windows Forms controls.

New Concepts

The .NET Framework 2.0 and Visual Studio 2005 introduce many new features to Windows Forms development that will have a broad impact on how you work with Windows Forms controls at both design time and run time. These features affect a wide range of behaviors, including control layout and positioning, run-time data entry, and application configuration and personalization.

Margins and Padding

Ensuring that your controls are positioned and spaced consistently is important for creating applications that are easy to learn and navigate. Unfortunately, the process of positioning controls is at best laborious and time consuming. One aspect of proper positioning involves making sure that there is a consistent amount of space between controls. For example, you might have a series of buttons at the bottom of a form that need to have exactly ten pixels of space between each of them. This generally involves placing one button, recording its Left property and modifying the Left property of the next button to the desired amount. Another example is when you have a container control and you want to make sure that constituent controls are no closer than eight pixels from the edge of the container. At a minimum, this setup involves placing the first control to serve as an anchor point and then aligning the other controls to it as appropriate.

The .NET Framework 2.0 introduces two new concepts, margins and padding, to controls that greatly simplify the work involved in scenarios like those just mentioned. Margin is the external space between two controls, while padding is the internal space between a control's edge and its contents. So, the right edge of one button and the left edge of another button is the margin between them. On the other hand, the space between a panel's edge and its constituent controls is the panel's padding. The Control class now has Padding and Margin properties so that a control can declare and enforce its spacing requirements.

The Margin and Padding properties are used by the Visual Studio IDE at design time to provide margin and padding snapline indicators. Both of these properties are of the Padding type, which is a simple structure that allows you to provide unique values for each edge of the control: Top, Bottom, Left, and Right. So, if you have a Panel whose Padding.Left is set to 5, and you are placing a child control on the Panel, the IDE will automatically provide you with feedback when the left side of the child control is five pixels from the left side of the Panel. This allows you to quickly place controls exactly where they need to be without having to manually set location properties. These properties are also honored at run time as controls are resized or relocated.

Aa730862.netvbdev0504(en-US,VS.80).gif

Figure 4. Snaplines based on Margin property

Auto-Completion

If you have used Internet Explorer, you have seen auto-completion in action. Auto-completion is the behavior you see when you enter data in a text control and the system automatically suggests what it thinks you might be entering. This feature is generally most beneficial when the user has to enter strings that are either long or complex. A prerequisite necessary for an auto-completion solution to work is the existence of some set of data that the system can use to look up possible matches.

You can now easily add auto-completion support to text boxes and combo boxes in your Windows Forms applications. Both controls have three new properties: AutoCompleteMode, AutoCompleteSource, and AutoCompleteCustomSource. You enable auto-completion by setting the AutoCompleteMode to Append, Suggest, or SuggestAppend. Setting AutoCompleteMode to Append results in the most likely match being automatically appended to the current data. Using Suggest results in a drop-down list populated with one or more suggested completion strings. SuggestAppend performs both tasks. The control also needs a source list from which it can search for suggestions as the user enters data. The AutoCompleteSource property allows you to select from some system sources such as FileSystem, HistoryList, RecentlyUsedList, AllUrl, and CustomSource.

If you select CustomSource, you must provide a list of strings to the AutoCompleteCustomSource property. This can be done at either design time or run time. Custom sources are very powerful, as they allow you to provide auto-complete behavior for business data. For example, you could query a list of product categories from a database when the form loads and supply a list of category names to serve as both the display source and auto-complete source for a combo box. This approach would allow your users to quickly select a category without having to enter the full category name or manually navigate through a long list of items.

Aa730862.netvbdev0505(en-US,VS.80).gif

Figure 5. Auto-complete support in Windows Forms

Configuration

The .NET Framework 1.1 provides a basic application configuration mechanism that allows you to define read-only application settings in the application configuration file. You access these settings through the System.Configuration.AppSettings class, which retrieves settings by key and returns a weakly typed object that you must cast to an appropriate type. This mechanism is useful for simple scenarios focused on relatively static data that is generally modified only by an administrator. However, many other application configuration scenarios require a more robust and flexible solution. The .NET Framework 2.0 and Visual Studio 2005 provide a new configuration system for Windows Forms applications. This system addresses the limitations of the previous solution and introduces many new concepts that result in a more integrated and efficient design-time experience and a more personalized end-user experience.

Important   From this point forward, "configuration system" refers to the new configuration system provided by the .NET Framework 2.0 and Visual Studio 2005.

Configuration Settings

The configuration system provides much more robust support for the definition, reading, and writing of configuration settings. Each setting is defined by its name, data type, scope, default value, and accessibility. All settings are strongly typed, and you can specify any serializable type.

You can also define a setting to have one of two scopes, User or Application. Application settings are read-only, and their value is shared across all users of an application on a machine. By default, these values are stored in the application configuration file, and cannot be modified by the user at runtime. User settings are stored and managed on a per-user basis and stored in user.config files. You can configure user settings to be read/write or read-only. A major feature of user settings is the configuration system's support for roaming Windows profiles. If you specify that user settings should roam with the user's Windows profile, those settings will automatically follow them when they run the application from another machine. The following is an example of a configuration setting:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <userSettings>
        <WindowsApplication1.My.MySettings>
            <setting name="DefaultView" serializeAs="String">
                <value>Normal</value>
            </setting>
        </WindowsApplication1.My.MySettings>
    </userSettings>
</configuration>

Wrapper Classes   The configuration system generates wrapper classes to access the settings stored in the configuration store. These wrapper classes provide the strongly typed interface to the configuration system and provide metadata that fully describes each setting.

You use the wrapper class in your application code to access and modify your configuration settings. For example, the following code retrieves the NetworkCredential stored in the user setting named Credentials.

Dim  cred  as  NetworkCredential  =  My.Settings.Credentials

IDE Support   Visual Studio 2005 provides full IDE support for both tasks. In Visual Basic .NET, you can access the Settings Designer by double-clicking My Project in the Solution Explorer and selecting the Settings tab. This presents a designer that allows you to define all aspects of your application and user settings. When you save your changes in the designer, Visual Basic will automatically create and populate the appropriate configuration files. It will also create a wrapper class and make it accessible through the My Object as My.Settings.

Aa730862.netvbdev0506(en-US,VS.80).gif

Figure 6. Making settings in Visual Studio 2005

Visual Studio also fully integrates your settings into the Windows Forms design experience to provide a convenient mechanism for binding control properties to application and user settings. The design experience is similar to what exists today for data binding. There is a new section in the Properties window named (ApplicationSettings). When you select this property, you are presented with a dialog that lets you bind individual control properties to configuration settings. Because settings are strongly typed, the IDE can even filter the list of available settings to only show those that are compatible with the type of the currently selected property. The code generated by this process handles populating a control's properties from setting values. When the application exits, the settings are automatically saved to the users' Application Data folder.

Walkthrough

This walkthrough demonstrates how you can use padding, auto-completion, and the new configuration system to create more powerful user interfaces.

Using Padding

A design goal of this application was to examine easy ways to replicate the look and feel of Microsoft Office applications. For example, Microsoft Outlook organizes functional areas of the interface into panels separated by movable splitters. Each visual panel has a single pixel and a dark blue border, and there is consistent spacing around the outside of and between the panels. You can use many combinations of controls to achieve this look, and this application examines one of them.

The main container control is the SplitContainer, which displays the history list and some buttons on the left and displays the Web and document content on the right. The SplitContainer consists of two Panels separated by a Splitter. Although the Panel control does not allow you to specify a border color directly, you can still easily achieve the look described previously. First, set the Panel control's BorderStyle property to None. Next, set the BackColor property to your desired border color. Finally, set the Padding.All property to define the width of your border. Now, when you place a control on the Panel and set its Dock property to Fill, the Panel will provide a colored border around your control.

Using Auto-Completion

The Address text box in the tool strip uses auto-completion to suggest URLs to resources as you type them in. If you select the tool strip text box, you will see that its AutoCompleteMode property is set to SuggestAppend. This setting is consistent with Internet Explorer's auto-completion behavior. The AutoCompleteSource property changes based on what type of resource you are searching for. When you click either the Documents or Web Pages buttons in the bottom-left corner of the form, the event handler performs some basic state maintenance tasks on the interface. One of these tasks is to change the AutoCompleteSource of the text box. If the user clicked the Web Pages button, the AutoCompleteSource is set to provide suggestions from all resolvable URLs. If the user clicked the Documents button, the AutoCompleteSource is set to just use the file system:

AddressToolStripTextBox.AutoCompleteSource = AutoCompleteSource.AllUrl
.
.
.
AddressToolStripTextBox.AutoCompleteSource = AutoCompleteSource.FileSystem

You can test this behavior by running the application, clicking the Web Pages button, and entering a URL starting with http://. You should see a list of suggestions automatically appear in a drop-down list under the text box. If you enter a file path staring with a drive letter, such as C://, you should not get any suggestions. Next, click the Documents button and again enter a URL starting with http://. This time you should not get any suggestions because the AutoCompleteSource is using only the file system.

Using the New Configuration System

This application uses the configuration system to provide personalization services to users by automatically saving some interface state when the form closes. This information is reloaded when the application starts so that the user is presented with the interface just the way she left it. In particular, the application stores the position of the splitter in the SplitPanel and WindowState of the form between user sessions.

If you want to see where the configuration files and wrapper classes reside, click the Show All Files button in Solution Explorer and expand My Project. Under My Project, you will see Settings.settings and Settings.Designer.vb. Settings.settings is the XML configuration file containing the settings definitions. Settings.Designer.vb is the wrapper class that provides access to these settings.

Conclusion

Margins and padding, auto-completion, and the new configuration system represent some of the major advances in Windows Forms technology that are be available with the release of Visual Studio 2005. These features have a broad impact on the Windows Forms experience for both developers and end users. Developer productivity enhancements such as margins and padding allow you to lay out interfaces more efficiently and with greater consistency. End-user productivity enhancements such as auto-completion allow users to complete tasks faster and with less opportunity for error. Finally, the improved configuration system offers new levels of flexibility, management, customization, and personalization to all Windows Forms applications.

Show: