Inheriting from Other Controls
Because inheritance is central to the
way controls work in the Windows Forms framework, we are not limited
to deriving from forms or composite controls. In principle, we can
use any control as a base class (unless it has marked itself as
sealed
in C# or NonInheritable
in VB, but very few controls do this). We must live without the
convenience of visual editing when deriving from other control types,
but of course that is also the case when we write custom controls.
The usual reason for inheriting from some non-composite control
(e.g., one of the built-in controls) is to provide a version of that
control with some useful extra feature. For example, we will see
later how to add an autocompletion facility to the
TextBox
control. As always, it is crucially
important only to use inheritance where it makes
sense—developers must be able to use our derived control just
as they would use the base control.
Visual Studio .NET does not provide a direct way of creating a new
derived control with a non-composite base class. However, it is
reasonably easy to get started: simply add a new Custom Control to
the project, delete the OnPaint
method it
supplies, and change the base class from Control
to whichever control class you want to derive from. Alternatively, just create a new normal class definition from scratch that inherits from the base class of your choice. (These two techniques are exactly equivalent. Although it is more straightforward just to create a normal ...
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.