Chapter 5. Building Controls

Windows Forms provides a rich array of built-in controls. It allows you to customize their behavior and, to some extent, their appearance. But powerful as these controls are, it is very useful to be able to augment this toolkit of standard user interface elements with controls of your own devising.

There are several ways in which you can define your own controls. The easiest is to create a composite control—a user interface element built out of a collection of other controls. This has the virtue of being simple, but sometimes you will require greater flexibility. You can write a custom control, where you dictate all aspects of its behavior. You can also create classes that inherit from other controls.

All user interface elements derive from the Control class, and any that you write are no exception. This means that even when writing a custom control, you can rely on the base class to supply all the required basic functionality; you only need to write code for the behavior unique to your control.

In this chapter, we will look at how to compose a group of controls into a single reusable user interface element with the UserControl class. We will then see how to write your own custom control from scratch. Finally we will look at some of the software design issues that user-defined controls must deal with.

Composite Controls

The built-in controls are undeniably very useful—almost every Windows application uses them. Not only does this avoid reinventing the wheel, ...

Get .NET Windows Forms in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.