Windows Forms 2.0: The Improvements


One of the key goals of Windows Forms 2.0 was to improve developer productivity. This goal manifests itself in the framework as a swath of tweaks and additions in your favorite programming languages, with enhancements like generics for C# and VS05 and an explosion of designer support. Additionally, there have been wholesale improvements to the key technology subsets, including settings, resources, data binding, and ClickOnce deployment. The following sections list some of the most significant.

Forms

As you would expect, System.Windows.Forms.Formthe heart and soul of Windows Forms developmenthas undergone a variety of enhancements as part of the Windows Forms evolution. In addition to a host of new properties, methods, and events for general form use, several sets of new members enable some of the more interesting advances, which we discuss next. Alternatively, you can dive straight into Chapter 2: Forms and Chapter 4: Layout for in-depth discussion of most of these.

Richer Control Validation

Windows Forms 1.x did provide a validation framework to support both control-by-control and formwide validation. However, it didn't provide a framework that allowed you to easily implement validation to let users freely navigate controls irrespective of the correctness of entered data. Instead, you had to write additional code both to avoid retaining focus on invalid controls and to make sure that all controls are validated when an OK button is clicked.

Windows Forms 2.0 improves the situation by allowing you to write the minimum validation code required for each control, and by letting you choose whether to retain focus on an invalid control. Additionally, formwide validation has been encapsulated in a way that allows you to validate either all the controls hosted by a form, or one of several subsets of those controls, including those that can be tabbed to, are selectable, or are visible. Chapter 3: Dialogs provides a complete discussion of Windows Forms 2.0 validation.

New Form Project Item Templates

VS05 offers two new form project item templates for Windows Forms 2.0. The first, covered in Chapter 2, allows you to create an MDI parent form implementation, complete with the basic UI elements and the functionality to make it all work. Although basic MDI parent forms are generally consistent enough to be supported by template generation, the uniqueness of an MDI application lies in the MDI child forms, which you need to build yourself. Luckily, the generated MDI parent form makes it easy to integrate the MDI child form.

The second template produces a stock standard, functional About box that you can use directly or easily tailor to your needs.

SnapLines Layout Mode

Although grid-style layout helps you position and size your controls on the UI, it enforces a rigid model. Grid-style layout is retained in Windows Forms 2.0, but a more useful and flexible layout style, SnapLines, is also included. SnapLines layout is more free-form, allowing you to drag your controls around a form and automatically snapping them into positions determined by horizontal or vertical alignment with other controls. The same thing applies when you resize your controls after they're hosted on a form. As explained in Chapter 4, SnapLines-style layout is powerful and simple, and it more easily supports your specific layout approach than does grid-style layout.

Margins and Padding

Just as SnapLines-style layout affords a more free-form and no less accurate layout experience than grid-style layout, the new Margin and Padding properties for forms and controls give you a free-form mechanism for specifying explicit margins between controls and between the form and other controls, as well as explicit padding within each control. Both properties are also used by SnapLines layout to snap controls to positions based on proximity to other controls, form edges, and contained text. See Chapter 4 for details.

Specialized Layout Controls

Sometimes, layout requirements are more complex than those you can easily or quickly establish using fundamentals like margins and padding. To aid you in several complex layout scenarios, Windows Forms 2.0 has introduced three new controls. SplitContainer basically evolves the Splitter control of Windows Forms 1.x fame into a full-fledged container control with a splitter bar and two adjacent panels to host child controls. More complex, web-style layout scenarios are enabled by the other two new controls: FlowLayoutPanel and TableLayoutPanel. FlowLayoutPanel is a container control that collapses and expands child controls in similar fashion to HTML web pages. Similarly, TableLayoutPanel supports web-style table layout, complete with margins, columns, and spanning, as well as fixed and proportional sizing. These layout tools are covered in Chapter 4 and Chapter 10: Controls.

Automatic Form Resizing

No matter how much layout support you have, you still need to expend a little effort in the Windows Forms Designer to adjust, fiddle, and tweak the form and hosted controls until they fit nicely together. Sometimes, this means expanding the form's client area to contain more, bigger, or taller controls. Sometimes, it means shrinking the form's client area when the reverse is true. All the time, you can configure a form to automatically grow and shrink in either situation and save yourself some effort, all thanks to the new AutoSize and AutoSizeMode properties, which are explored in Chapter 4.

Drawing

Although drawing, in general, enjoys only modest enhancements, a few specific features are not only worth calling out but also getting to know, including support for screen dumping, high-performance text rendering, and enhanced double buffering.

Native Screen Dumping Support

When you explore Windows Forms 2.0 and .NET 2.0, you'll find a wide variety of new types and members that simplify your life by encapsulating functionality whose implementation required an inordinate amount of time in Windows Forms 1.x and .NET 1.x. The ability to provide screen captures is one example. It's enabled with a single method, it's a lot of fun, and it's covered in Chapter 5: Drawing Basics.

TextRenderer: GDI-Based Text Drawing

As in .NET 1.x, System.Drawing still provides a managed wrapper around the GDI+ API. GDI+ has all kinds of wonderful features (covered in Chapter 5: Drawing Basics, Chapter 6: Drawing Text, and Chapter 7: Advanced Drawing), but for the most accurate character set support for internationalization, and for output that looks just like the shell, you need the more seasoned GDI API. Although parts of the API haven't been wrapped, for text rendering, GDI is provided by the TextRenderer class in the System.Windows.Forms namespace. For more information about TextRenderer and the pros and cons of using it, see Chapter 6.

Enhanced Double Buffering

Double buffering is a technique by which you force one or more paint operations to take place in memory before blatting the results to the screen in one fell swoop. This technique has the advantage of producing markedly fewer flickers (ideally, none). Double buffering existed in Windows Forms 1.x, but you had to switch it on from code and it was somewhat more complicated than it needed to be. Now, double buffering can be triggered from a single form property, DoubleBuffered. Further, if you prefer more control of the way double buffering is used in your application, you can have it by using a suite of new types in the System.Drawing namespace. Double buffering is discussed in Chapter 7: Advanced Drawing.

Printing

A variety of tweaks across the existing System.Drawing.Printing namespace have enhanced printing support for Windows Forms applications. One example is the ability to determine whether users are printing to a printer, a file, or simply to a preview, all integrated with the existing print dialogs.Another example is the provision of more robust and more accurate output device measurements. Chapter 8: Printing explains this and many more improvements.

Components and Controls

Apart from a host of updates to the existing set of intrinsic Windows Forms components and controls, Windows Forms 2.0 includes several key new components and controls and additional Windows Forms Designer support for using them.

Office 2003-Style Tool Strip Controls

Arguably one of the most sought after features of any Windows Forms development platform is the ability to create UIs that look and feel like contemporary Microsoft applications such as Word, Excel, and Outlook. Central to this theme are the most common of all form adornments: menu strips, tool strips, status strips, and context menus. All these are exposed from Windows Forms 2.0 as a set of tool strip controls that provides the same appearance and functionality you expect from contemporary Microsoft applications such as Office 2003.

The tool strip suite is so important to Windows Forms that it's covered here in several chapters. Their frequent use on forms is covered in Chapter 2, along with MDI menu merging. When added to forms, tool strips are susceptible to being dragged around and resized, and Chapter 4 shows you how they capably cope with copious amounts of dynamic layout issues.

You can also dynamically update tool strip UIs using specialized customization enabled by theme-sensitive custom renderers, as discussed in Chapter 10. Tool strips can be dragged around the edges of a form, and that requires that they remember where they were and how big they were from one application session to the next. You can easily accomplish this using Windows Forms settings, as covered in Chapter 15: Settings. Finally, the tool strip suite is readily extensible, a case in point being BindingNavigator, which is discussed in Chapter 16: Data Binding Basics.

The DataGridView Control

Data presentation and manipulation are a major focus of Windows Forms applications. One of the most common ways to do this is to use a grid control. Although the DataGrid control from Windows Forms 1.x provided a solid, basic grid control implementation, it didn't go far enough to meet the demands of developers.

Microsoft responded to customer feedback and developed DataGridView, a wholly new grid control that offers a significantly more functional, configurable, and customizable grid experience than its predecessor. As you would expect, DataGridView is equally happy in bound and unbound scenarios, as well as offering virtualization. Unfortunately (or fortunately, depending on how you look at it), DataGridView is too powerful to be comprehensively covered in this book.[2] However, this book provides an overview in Chapter 10 and demonstrates its data binding capabilities in Chapter 16 and Chapter 17: Applied Data Binding.

[2] Brian Noyes covers it nicely in Data Binding with Windows Forms 2.0: Programming Smart Client Data Applications with .NET (Addison-Wesley, 2006).

The MaskedTextBox Control

Another long-sought-after control in Windows Forms provides masked text entry to display detailed information to users about what sort of data needs to be entered before they enter it. The new Windows Forms 2.0 MaskedTextBox control natively provides this support. An overview of MaskedTextBox is provided in Chapter 3.

The WebBrowser Control

As ironic as it sounds, there is a demand for displaying web pages from Windows Forms applications, particularly when it comes to rich content that's persisted as HTML. This was certainly possible with Windows Forms 1.x, but it required on interop with native Internet Explorer APIs. This technique is more complex than simply using a native .NET control, which Windows Forms 2.0 now includes. A brief exposé is provided in Appendix D: Component and Control Survey.

Smart Tag Design-Time Configuration

Components and controls have been configurable from a Properties window for a lot longer than .NET has been around. However, using the Properties window is not always the most efficient way to configure components and controls, particularly when you need to wade through tens or hundreds of properties to find the few you most often adjust. Rather than bring you to the mountain, Microsoft brings the mountain to you in the form of smart tags. The Windows Forms Designer uses smart tags to present the most common configurations for a control or component right next to it in the design surface, ultimately reducing the time you spend configuring.

Design-Time Integration

Design-Time integration may not be the most approachable of technologies, but it is certainly one you need to become familiar with to produce high-quality custom controls and components. Fortunately, the .NET and VS05 design-time infrastructure is nothing if not rich, and it is certainly richer with Windows Forms 2.0.

New Design-Time Attributes

Attributes provide the easiest path to influencing design-time integration of custom components and controls. There are several new attributes in Windows Forms 2.0, such as the DisplayName attribute, which allows you to change a property's text label in the Properties window from the raw property name. All new attributes are detailed in Chapter 11: Design-Time Integration: The Properties Window.

Granular Control of Form Initialization

Design-time components implement the popular ISupportInitialize interface for scenarios where the initialization of one or more properties is dependent on one more properties exposed by the same design-time component. However, sometimes one design-time component can't be initialized until another design-time component that it depends on has been initialized. ISupportInitialize doesn't cater to this situation, but the new ISupportInitializeNotification interface does, and it is described in Chapter 11.

Custom Smart Tag Support

Just as the intrinsic Windows Forms 2.0 components and controls employ smart tags to enhance the design-time configuration experience, your custom design-time components can leverage the same infrastructure to provide their own smart tag support. The infrastructure is rich enough that its coverage takes a chapter, Chapter 12: Design-Time Integration: Designers and Smart Tags. Smart tags are a must if you want to produce highly polished and usable custom design-time components.

Resources

Resource support in VS05, .NET, and Windows Forms 2.0 has undergone a host of improvements that ultimately make it easier for you to configure, manage, and code with resources. Take a look at Chapter 13: Resources for the good oil on resources.

Visual Resource Editor in Visual Studio 2005

Visual Studio .NET 200x and Windows Forms 1.x included an editor for managing resources, but it lacked luster, particularly because it was text-based, whereas many resources used by applications (images, icons, audio files, and text files) are visual and aural. Visual Studio 2005 and Windows Forms 2.0 provide a brand new, visual resource editor that simplifies the management of resources in a way that allows you to see or hear those resources as users will experience them at run-time.

Linked and Embedded Resources

Before Windows Forms 2.0, resources were managed by VS05. In the real world, applications may require resources that are not under the domain of either developers or VS05, and commercial-grade graphics applications are vastly superior to those that VS05 can provide. Graphical content is probably the most well known of these sorts of resources, and often it is produced, not by developers, but by a different group of people in a different location.

To facilitate this working arrangement, Windows Forms 2.0 allows you to link resources from VS05 at design time and embed them only at compile time. This loose coupling between resources and code allows graphics specialists to freely manipulate graphics during development independently of developers.

Strongly Typed Resources

.NET 1.x provided a variety of types to use in acquiring resources from code at run time, although using them required a nontrivial amount of code and they were type safe only insofar as they differentiated between string and object resources. Windows Forms 2.0 solves these problems by encapsulating both your application resources and the code to access them via a Designer-generated class that exposes each resource as a strongly typed property. Not only does this technique reduce the amount of the needed code to one line, but it also means that you can pick up resource coding errors at compile time, thanks to strong typing.

Full Right-to-Left Internationalization Support

Right-to-left support for Windows Forms 1.x applications was available, although not 100% consistent. However, with Windows Forms 2.0, creating right-to-left-oriented applications is not only 100% consistent but also integrated with internationalization support. That is really handy when half the world reads right-to-left. This feature is important when you want to make lots of money selling your application around the world.

Applications

There are many styles of Windows Forms applications, including single-document interface (SDI) and multiple-document interface (MDI). Variations of these, such as multi-SDI and single-MDI applications, rely on single instancing to enforce their unique models. Single instancing is possible for Windows Forms 1.x applications if you use a complex arrangement of code built on remoting. Windows Forms 2.0 applications can simply leverage the beauty of .NET and hijack new Visual Basic classes for single instancing. Chapter 14: Applications covers the gamut of scenarios that depend on single instancing.

Settings

The Windows Forms 1.x settings system has undergone an almost complete overhaul to produce a rich, Windows Forms Designer-integrated infrastructure for creating, managing, and deploying application, user, and roaming-user settings to one or more data stores. The settings system is discussed in its entirety in Chapter 15.

Visual Studio 2005 and Windows Forms Designer Enhancements

VS05 includes a Settings Editor that allows you to easily create, manage, and configure application, user, and roaming-user settings for all simple types and a wide variety of complex types. Additionally, you can bind control properties to settings via the Properties window, which has built-in support for doing so. Either way, you don't have to write code to create or load settings, and you need only a single line of code to save updated settings. The minimalist coding requirements and sweet designers alone are substantial improvements over the settings support found in Windows Forms 1.x. But wait, there's more.

Strongly Typed Settings

As with resources, accessing settings before Windows Forms 2.0 required extensive coding and a distinct lack of type safety. Also, Windows Forms 2.0 automatically encapsulates the mechanics of dealing with settings from a single Designer-generated wrapper class that exposes settings as strongly typed properties. Significant code reduction, readability, and maintainability are the benefits.

Rich Programmatic Support

The problem with settings is that they change; they can change not only from one installation to the next but also from one version to the next and even from one session to the next. These scenarios can work well only with support for loading, updating, saving, rolling back, and migrating settings. Fortunately, Windows Forms 2.0 and .NET 2.0 provide comprehensive programmatic support for all of them.

Safe Settings Persistence

In Windows Forms 1.x, an application that was fully trusted by the client machine it was executing on had complete access to all system resources, including memory, local hard drives, and the Registry. However, partially trusted applications might not have the same luxury. In particular, if an application needed to load and save application and user settings, you had to write special code to use isolated storage. Unfortunately, this turned out to be a lot of work. What's nice about Windows Forms 2.0 is that the settings system is equally safe and requires only one line of code to save any changed user settings. Even better, the same model is used for partial and full trust execution, making it compatible with ClickOnce. This deployment technology is covered in Chapter 19: ClickOnce Deployment.

Settings Provider Model

By default, the settings system persists settings to the local file system. However, settings are often available from a variety of data stores, such as web services and the Registry. To give Windows Forms applications the freedom to choose where their settings will be persisted to, the settings system is built on the idea of settings providers. A settings provider is a special implementation that knows how to load and save settings located in a specific data store. They all implement the same interface to allow them to plug in to the settings system as required. The default is LocalFileSettingsProvider, although you can create your own, as described in the .NET Framework 2.0 SDK.

Data Binding

Data binding is about making it easier to build UIs that operate over data. In Windows Forms 2.0, data binding is more full featured because of the new BindingSource component. BindingSource's primary role is to act as a data-binding-savvy data source for types that aren't data binding savvy. This simple ability facilitates the creation of a single-client code model to operate over data sources independent of the type from which a data source is instantiated. Coupled with increased data binding integration into the Windows Forms code base, Windows Forms 2.0 data binding provides a big hook on which VS05 and the Windows Forms Designer hang the most extensive set of design-time features yet devised for creating and managing data-bound UIs.

Unification of Heterogeneous Data Sources

When you think "data source," you are likely to think of the most popular type: the typed data set. However, data sources come in many shapes and sizes, including relational, hierarchical, and object. All these could be bound to in Windows Forms 1.x, but each provided a different level of data binding integration. This had the effect of forcing developers to employ different coding models to suit, or potentially to spend a nontrivial amount of time building extra support for their data sources, such as implementing IBindingList, to achieve higher levels of data binding integration.

Windows Forms 2.0 addresses this problem with the BindingSource component, which is fundamentally capable of consuming any of these data sources and re-exposing them via a single, unified implementation to provide a consistent client coding model. Additionally, any data sources that have less than IBindingList levels of implementation are automatically "upgraded" to support IBindingList. This means that you can write a simple class as an item data source and use BindingSource to automatically convert it into a full list data source, with no extra code.

Richer Design-Time Configuration Support

If you like the idea of writing less code, then you'll love the addition of several new Windows Forms Designer features. The first of these is the Data Sources window, which allows you to either create or locate data sources to bind to. After the data source is acquired, you can drag it from the Data Sources window onto your form, and the Windows Forms Designer automatically creates either a details or a grid view style of UI for you. That is a major time-saver, especially when you consider that the Windows Forms Designer not only creates the controls and binds them as necessary, but also creates decent names for all controls involved. This works for any data source that can be consumed by the BindingSource component, so all your data sources can enjoy this feature.

Tool Strip-Style Data Source Navigation

The BindingSource component also incorporates currency management, thereby saving you the effort of finding, inspecting, and using one yourself, a common endeavor in Windows Forms 1.x to support data source navigation and editing. Although you could write code to leverage BindingSource's currency implementation, you would be better served by dropping a BindingNavigator onto a form and binding it to BindingSource. BindingNavigator has specific knowledge of BindingSource that allows it to automatically expose VCR-style navigation, along with various kinds of editing support. Further, the Windows Forms Designer automatically adds a BindingNavigator to a form when a data source is dropped onto it from the Data Sources window.

Tighter Integration with Form Validation

Windows Forms 1.x data binding provided a variety of hooks by which you could integrate with and influence the data binding process, but there were some areas that didn't, particularly those involved with validation of bound controls. When the value of a bound control was changed, data binding would automatically update the bound value in the data source, whether or not the data was valid. Additionally, any change was rolled back if the data could not be converted to the type of value on the data source. This made it difficult to support free-form UI data entry, which is the nominal user experience for Windows Forms applications.

Windows Forms 2.0 allows you to control exactly when the data source is updated after a bound control's value changes, including immediately, after it is successfully validated, or never. Thus, you can enjoy the freedom granted by Windows Forms 2.0's updated validation model and integrate nicely with data binding after a simple configuration.

Multithreaded User Interfaces

Long-running operations are common in Windows Forms applications, and they can cause your UIs to lock up if you don't use multithreading techniques to create additional worker threads. Achieving safe multithreading was a bother in Windows Forms 1.x. As is common with Windows Forms 2.0, you'll find multithreading greatly simplified. Chapter 18: Multithreaded User Interfaces has more details.

The BackgroundWorker Component

Previously, if you wanted to create a safe multithreading implementation to asynchronously spin off long-running operations onto worker threads, you had to make a serious coding investment that depended on an extensive knowledge of delegates and message passing. Now, BackgroundWorker encapsulates the communication complexities to provide a vastly simplified framework for spinning off worker threads, safely monitoring progress and completion, and easily incorporating cancellation.

Improved Support for Asynchronous Invocation of Web Service Methods

BackgroundWorker allows you to call web services asynchronously if you like, but the same underlying technology that BackgroundWorker depends on has been factored into the base class used to implement your web service client proxy classes. This lets you drop a web service component onto your form, allowing you to call them synchronously or asynchronously as you choose. And how do web services get into your Toolbox? They're added automatically whenever you create a new web reference.

ClickOnce Deployment

Web deployment for applications was available for Windows Forms 1.x developers via No-Touch Deployment (NTD), and it paved the way for a deployment experience that was fundamentally as easy as that for web applications. However, NTD fell far short in ease of use, configuration, and debugging (so much so that it's been disabled in Windows Forms 2.0 for Internet deployment). In Windows Forms 2.0, NTD has been replaced by the eminently more secure and configurable ClickOnce deployment. ClickOnce is a strategic technology that will support applications well into the future, although you can enjoy it right now by reading Chapter 19: ClickOnce Deployment.

Automatic Publishing, Delivery, and Installation

At the heart of ClickOnce is a simple deployment model that automatically takes care of publishing your Windows Forms application from VS05 to one of several publish locations, such as web sites or network file shares. Additionally, ClickOnce downloads and installs published applications (if permitted by the user). Users need only select the appropriate deployment manifest, a task that, for web sites, requires navigating to an appropriate web page (which ClickOnce generates for you) and clicking on the appropriate link.

Tight Visual Studio 2005 Integration and Configuration

An application's ClickOnce Deployment settings can be wholly configured from VS05. This support includes the ability to specify both installation prerequisites (such as .NET 2.0) and file dependencies, as well as to publish location and versioning requirements and specify alternative publishing and upgrade locations.

Trustworthy Deployment

Because deployment of Windows Forms applications with ClickOnce will occur most often from a web site, security needs to be involved. ClickOnce employs two key security models: Authenticode and code access security (CAS). Authenticode, a technology for trusting publishers, requires that a publisher's applications be digitally signed, with certificates issued by trusted certification authorities such as VeriSign. All ClickOnce-deployed Windows Forms applications must be digitally signed and, when requested by a user, display information about the publisher. This lets the user decide whether to actually download and install the application, and it provides recourse in the event that the code is dodgy. When downloaded and installed, an application executes within a CAS-managed security sandbox that allows only a predefined set of permissions, depending on the zone from which the application is deployed (the Internet, a local intranet, or the current machine). If the permissions required by an application exceed those provided by a particular zone, users are given the option to cancel the download or to grant the needed permissions.




Windows Forms 2.0 Programming
Windows Forms 2.0 Programming (Microsoft .NET Development Series)
ISBN: 0321267966
EAN: 2147483647
Year: 2006
Pages: 216

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net