Home > Articles

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.

09fig01.gifFigure 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.

09fig02.gifFigure 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.

09fig03.jpgFigure 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.

09fig04.jpgFigure 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020