Design-Time Integration

With just a little effort, you can integrate nonvisual components and controls very tightly into the C# design-time environment, providing a rich development experience for the programmer who uses the custom components and controls that you build. Chris Sells shows you what's involved, in this sample chapter from Windows Forms Programming in C#.

This chapter is from the book

This chapter is from the book

A component is a nonvisual class designed specifically to integrate with a design-time environment such as Visual Studio .NET.
WinForms provides several standard components, and .NET lets you build your own, gaining a great deal of design-time integration
with very little work.

On the other hand, with a bit more effort, you can integrate nonvisual components and controls very tightly into the design-time
environment, providing a rich development experience for the programmer using your custom components and controls.

Components

Recall from Chapter 8: Controls that controls gain integration into VS.NET merely by deriving from the Control base class in the System.Windows.Forms
namespace. That's not the whole story. What makes a control special is that it's one kind of component: a .NET class that integrates with a design-time environment such as VS.NET. A component can show up on the Toolbox along
with controls and can be dropped onto any design surface. Dropping a component onto a design surface makes it available to
set the property or handle the events in the Designer, just as a control is. Figure 9.1 shows the difference between a hosted control and a hosted component.

Standard Components

It's so useful to be able to create instances of nonvisual components and use the Designer to code against them that WinForms
comes with several components out of the box:

Standard dialogs.
The ColorDialog, FolderBrowserDialog, FontDialog, OpenFileDialog, PageSetupDialog, PrintDialog, PrintPreviewDialog, and SaveFileDialog
classes make up the bulk of the standard components that WinForms provides. The printing-related components are covered in
detail in Chapter 7: Printing.

Menus.
The MainMenu and ContextMenu components provide a form's menu bar and a control's context menu. They're both covered in detail
in Chapter 2: Forms.

User information.
The ErrorProvider, HelpProvider, and ToolTip components provide the user with varying degrees of help in using a form and
are covered in Chapter 2: Forms.

Notify icon.
The NotifyIcon component puts an icon on the shell's TaskBar, giving the user a way to interact with an application without
the screen real estate requirements of a window. For an example, see Appendix D: Standard WinForms Components and Controls.

Image List.
The ImageList component keeps track of a developer-provided list of images for use with controls that need images when drawing.
Chapter 8: Controls shows how to use them.

Timer.
The Timer component fires an event at a set interval measured in milliseconds.

Using Standard Components

What makes components useful is that they can be manipulated in the design-time environment. For example, imagine that you'd
like a user to be able to set an alarm in an application and to notify the user when the alarm goes off. You can implement
that using a Timer component. Dropping a Timer component onto a Form allows you to set the Enabled and Interval properties
as well as handle the Tick event in the Designer, which generates code such as the following into InitializeComponent:

As you have probably come to expect by now, the Designer-generated code looks very much like what you'd write yourself. What's
interesting about this sample InitializeComponent implementation is that when a new component is created, it's put on a list
with the other components on the form. This is similar to the Controls collection that is used by a form to keep track of
the controls on the form.

After the Designer has generated most of the Timer-related code for us, we can implement the rest of the alarm functionality
for our form:

In this sample, when the timer goes off every 100 milliseconds (the default value), we check to see whether we're within 1
second of the alarm. If we are, we shut off the alarm and notify the user, as shown in Figure 9.2.

A class that implements the IComponent interface can be added to the Toolbox1 in VS.NET and dropped onto a design surface. When you drop a component onto a form, it shows itself in a tray below the form.
Unlike controls, components don't draw themselves in a region on their container. In fact, you could think of components as
nonvisual controls, because, just like controls, components can be managed in the design-time environment. However, it's more
accurate to think of controls as visual components because controls implement IComponent, which is where they get their design-time
integration.

A Sample Component

As an example, to package the alarm functionality we built earlier around the Timer component, let's build an AlarmComponent
class. To create a new component class, right-click on the project and choose Add | Add Component, enter the name of your
component class, and press OK. You'll be greeted with a blank design surface, as shown in Figure 9.3.

The design surface for a component is meant to host other components for use in implementing your new component. For example,
we can drop our Timer component from the Toolbox onto the alarm component design surface. In this way, we can create and configure
a timer component just as if we were hosting the timer on a form. Figure 9.4 shows the alarm component with a timer component configured for our needs.

This implementation is just like what the form was doing before, except that the alarm date and time are set via the public
Alarm property; when the alarm sounds, an event is fired. Now we can simplify the form code to contain merely an instance
of the AlarmComponent, setting the Alarm property and handling the AlarmSounded event:

In this code, the form uses an instance of AlarmComponent, setting the Alarm property based on user input and handling the
AlarmSounded event when it's fired. The code does all this without any knowledge of the actual implementation, which is encapsulated
inside the AlarmComponent itself.

Component Resource Management

Although components and controls are similar as far as their design-time interaction is concerned, they are not identical.
The most obvious difference lies in the way they are drawn on the design surface. A less obvious difference is that the Designer
does not generate the same hosting code for components that it does for controls. Specifically, a component gets extra code
so that it can add itself to the container's list of components. When the container shuts down, it uses this list of components
to notify all the components that they can release any resources that they're holding.

Controls don't need this extra code because they already get the Closed event, which is an equivalent notification for most
purposes. To let the Designer know that it would like to be notified when its container goes away, a component can implement
a public constructor that takes a single argument of type IContainer:

public AlarmComponent(IContainer container) {
// Add object to container's list so that
// we get notified when the container goes away
container.Add(this);
InitializeComponent();
}

Notice that the constructor uses the passed container interface to add itself as a container component. In the presence of
this constructor, the Designer generates code that uses this constructor, passing it a container for the component to add
itself to. Recall that the code to create the AlarmComponent uses this special constructor:

As you may recall from Chapter 4: Drawing Basics, the client is responsible for calling the Dispose method from the IDisposable interface. The IContainer
interface derives from IDisposable, and the Container implementation of Dispose walks the list of components, calling IDisposable.
Dispose on each one. A component that has added itself to the container can override the Component base class's Dispose method
to catch the notification that is being disposed of:

Notice that, unlike the method that the client container is calling, the alarm component's Dispose method takes an argument.
The Component base class routes the implementation of IDisposable.Dispose() to call its own Dispose(bool) method, with the
Boolean argument disposing set to true. This is done to provide optimized, centralized resource management.

A disposing argument of true means that Dispose was called by a client that remembered to properly dispose of the component.
In the case of our alarm component, the only resources we have to reclaim are those of the timer component we're using to
provide our implementation, so we ask our own container to dispose of the components it's holding on our behalf. Because the
Designer-generated code added the timer to our container, that's all we need to do.

A disposing argument of false means that the client forgot to properly dispose of the object and that the .NET Garbage Collector
(GC) is calling our object's finalizer. A finalizer is a method that the GC calls when it's about to reclaim the memory associated with the object. Because the GC calls the finalizer at some indeterminate time—potentially long after the component is no longer needed (perhaps hours or
days later)—the finalizer is a bad place to reclaim resources, but it's better than not reclaiming them at all.

The Component base class's finalizer implementation calls the Dispose method, passing a disposing argument of false, which
indicates that the component shouldn't touch any of the managed objects it may contain. The other managed objects should remain
untouched because the GC may have already disposed of them, and their state is undefined.

Any component that contains other objects that implement IDisposable, or handles to unmanaged resources, should implement
the Dispose(bool) method to properly release those objects' resources when the component itself is being released by its container.