ComponentsRecall 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 ComponentsIt'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:
Using Standard ComponentsWhat 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: Sub InitializeComponent() Me.Components = New Container() Me.Timer1 = New Timer(Me.Components) ... ' timer1 Me.timer1.Enabled = True End Sub Public Sub timer1_Tick(sender As Object, e As EventArgs) _ Handles timer1.Tick ... End Sub 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: Dim alarm As DateTime = DateTime.MaxValue ' No alarm Sub setAlarmButton_Click(sender As Object, e As EventArgs) _ Handles setAlarmButton.Click Alarm = dateTimePicker1.Value End Sub ' Handle the Timer's Tick event Sub timer1_Tick(sender As Object, e As EventArgs) _ Handles timer1.Tick statusBar1.Text = DateTime.Now.TimeOfDay.ToString() ' Check to see whether we're within 1 second of the alarm Dim seconds As Single = DateTime.Now.Subtract(alarm).TotalSeconds If (seconds >= 0) And (seconds <= 1) Then Alarm = DateTime.MaxValue ' Show alarm only once MsgBox("Wake up!") End If End Sub 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 ComponentsA component is any class that implements the IComponent interface from the System.ComponentModel namespace: Interface IComponent Inherits IDisposable Property Site() As ISite Event Disposed() As EventHandler End Interface Interface IDisposable Sub Dispose() End Interface A class that implements the IComponent interface can be added to the Toolbox [1] 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 ComponentAs 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 view [2] for the component displays the following skeleton generated by the component project item template and filled in by the Designer for the timer:
Public Class AlarmComponents Inherits System.ComponentModel.Component #Region " Component Designer generated code " Public Sub New(Container As System.ComponentModel.IContainer) MyClass.New() ' Required for Windows.Forms Class Composition Designer support Container.Add(me) End Sub Public Sub New() MyBase.New() ' This call is required by the Component Designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call End Sub ' Component overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub ' Required by the Component Designer Private components As System.ComponentModel.IContainer ' NOTE: The following procedure is required by the Component Designer ' It can be modified using the Component Designer. ' Do not modify it using the code editor. Friend WithEvents Timer1 As System.Windows.Forms.Timer <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Me.components = New System.ComponentModel.Container() Me.Timer1 = New System.Windows.Forms.Timer(Me.components) End Sub #End Region End Class 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 Inherits System.ComponentModel.Component ... Dim _alarm As DateTime = DateTime.MaxValue ' No alarm Public Property Alarm() As DateTime Get Return Me._alarm End Get Set(ByVal Value As String) Me._alarm = Value End Set End Property ' Handle the Timer's Tick event Public Event AlarmSounded As EventHandler Public Sub timer1_Tick(sender As Object, e As System.EventArgs) _ Handles timer1.Tick ' Check to see whether we're within 1 second of the alarm Dim seconds As Double = (DateTime.Now Me.alarm).TotalSeconds If seconds >= 0 And seconds <= 1 Then _alarm = DateTime.MaxValue ' Show alarm only once RaiseEvent AlarmSounded(Me, EventArgs.Empty) End If End Sub End Class 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 Inherits Form Dim alarmComponent1 As AlarmComponent ... Sub InitializeComponent() ... Me.alarmComponent1 = New AlarmComponent(Me.components) ... AddHandler Me.alarmComponent1.AlarmSounded, _ AddressOf Me.alarmComponent1_AlarmSounded ... End Sub End Class Sub setAlarmButton_Click(sender As Object, e As EventArgs) _ Handles setAlarmButton.Click alarmComponent1.Alarm = dateTimePicker1.Value End Sub Sub alarmComponent1_AlarmSounded(sender As Object, e As EventArgs) _ Handles alarmComponent1.AlarmSounded MsgBox("Wake Up!") End Sub 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 ManagementAlthough 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 Sub New(container As IContainer) ' Add object to container's list so that ' we get notified when the container goes away container.Add(Me) InitializeComponent() End Sub 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 Inherits Form Dim components As IContainer Dim alarmComponent1 As AlarmComponent ... Sub InitializeComponent() Me.components = New Container() ... Me.alarmComponent1 = New AlarmComponent(Me.components) ... End Sub End Class 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 Inherits Form ... Dim components As Container ... ' Overridden from the base class Component.Dispose method Protected Overrides Sub Dispose(disposing As Boolean) If disposing Then If Not (Components Is Nothing) Then ' Call each component's Dispose method components.Dispose() End If End If MyBase.Dispose(disposing) End Sub End Class 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 Inherits Component Dim timer1 As Timer Dim components As IContainer ... Sub InitializeComponent() Me.components = New Container() Me.timer1 = New Timer(Me.components) ... End Sub Protected Overrides Sub Dispose(disposing As Boolean) If disposing Then ' Release managed resources ... ' Let contained components know to release their resources If Not (components Is Nothing) Then components.Dispose() End If End If ' Release unmanaged resources ... End Sub End Class 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(Boolean) 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 components, contains other objects that implement IDisposable, or contains handles to unmanaged resources should implement the Dispose(Boolean) method to properly release those objects' resources when the component itself is being released by its container. |