Design-Time Integration
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.
Figure 9.1. Locations of Components and Controls Hosted on a Form
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:
void InitializeComponent() { this.components = new Container(); this.timer1 = new Timer(this.components); ... // timer1 this.timer1.Enabled = true; this.timer1.Tick += new EventHandler(this.timer1_Tick); ... }
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:
DateTime alarm = DateTime.MaxValue; // No alarm void setAlarmButton_Click(object sender, EventArgs e) { alarm = dateTimePicker1.Value; } // Handle the Timer's Tick event void timer1_Tick(object sender, System.EventArgs e) { statusBar1.Text = DateTime.Now.TimeOfDay.ToString(); // Check to see whether we're within 1 second of the alarm double seconds = (DateTime.Now - alarm).TotalSeconds; if( (seconds >= 0) && (seconds <= 1) ) { alarm = DateTime.MaxValue; // Show alarm only once MessageBox.Show("Wake Up!"); } }
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.
Figure 9.2. The Timer Component Firing Every 100 Milliseconds
If this kind of single-fire alarm is useful in more than one spot in your application, you might choose to encapsulate this functionality in a custom component for reuse.
Custom Components
A component is any class that implements the IComponent interface from the System.ComponentModel namespace:
interface IComponent : IDisposable { ISite Site { get; set; } event EventHandler Disposed; } interface IDisposable { void Dispose(); }
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.
Figure 9.3. A New Component Design Surface
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.
Figure 9.4. A Component Design Surface Hosting a Timer Component
Switching to the code view2 for the component displays the following skeleton generated by the component project item template and filled in by the Designer for the timer:
using System; using System.ComponentModel; using System.Collections; using System.Diagnostics; namespace Components { /// <summary> /// Summary description for AlarmComponent. /// </summary> public class AlarmComponent : System.ComponentModel.Component { private Timer timer1; private System.ComponentModel.IContainer components; public AlarmComponent(System.ComponentModel.IContainer container) { /// <summary> /// Required for Windows.Forms Class Composition Designer support /// </summary> container.Add(this); InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } public AlarmComponent() { /// <summary> /// Required for Windows.Forms Class Composition Designer support /// </summary> InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.timer1 = new System.Windows.Forms.Timer(this.components); // // timer1 // this.timer1.Enabled = true; } #endregion } }
Notice that the custom component derives from the Component base class from the System.ComponentModel namespace. This class provides an implementation of IComponent for us.
After the timer is in place in the alarm component, it's a simple matter to move the alarm functionality from the form to the component by handling the timer's Tick event:
public class AlarmComponent : Component { ... DateTime alarm = DateTime.MaxValue; // No alarm public DateTime Alarm { get { return this.alarm; } set { this.alarm = value; } } // Handle the Timer's Tick event public event EventHandler AlarmSounded; void timer1_Tick(object sender, System.EventArgs e) { // Check to see whether we're within 1 second of the alarm double seconds = (DateTime.Now - this.alarm).TotalSeconds; if( (seconds >= 0) && (seconds <= 1) ) { this.alarm = DateTime.MaxValue; // Show alarm only once if( this.AlarmSounded != null ) { AlarmSounded(this, EventArgs.Empty); } } } }
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:
public class AlarmForm : Form { AlarmComponent alarmComponent1; ... void InitializeComponent() { ... this.alarmComponent1 = new AlarmComponent(this.components); ... this.alarmComponent1.AlarmSounded += new EventHandler(this.alarmComponent1_AlarmSounded); ... } } void setAlarmButton_Click(object sender, EventArgs e) { alarmComponent1.Alarm = dateTimePicker1.Value; } void alarmComponent1_AlarmSounded(object sender, EventArgs e) { MessageBox.Show("Wake Up!"); }
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:
public class AlarmForm : Form { IContainer components; AlarmComponent alarmComponent1; ... void InitializeComponent() { this.components = new Container(); ... this.alarmComponent1 = new AlarmComponent(this.components); ... } }
By default, most of the VS.NET-generated classes that contain components will notify each component in the container as part of the Dispose method implementation:
public class AlarmForm : Form { ... IContainer components; ... // Overridden from the base class Component.Dispose method protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { // Call each component's Dispose method components.Dispose(); } } base.Dispose( disposing ); } }
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:
public class AlarmComponent : Component { Timer timer1; IContainer components; ... void InitializeComponent() { this.components = new Container(); this.timer1 = new Timer(this.components); ... } protected override void Dispose(bool disposing) { if( disposing ) { // Release managed resources ... // Let contained components know to release their resources if( components != null ) { components.Dispose(); } } // Release unmanaged resources ... } }
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.