Creating Custom Controls from Scratch

Sooner or later, the Betty Crocker cookies just aren't exactly what you had in mind, and it is time to bake up a new control from scratch. In the previous examples, you derived first from an existing control type (e.g., Button) and then from UserControl. In the next example, you will derive from the base control type: Control.

Creating your control from scratch lets you manage the look and feel of your new control with precision. However, it also requires that you implement every aspect of the control, including painting it—that is, you get power, but at the cost of greater responsibility, a lesson to us all.

You'll create a control that provides the analog clock functionality you implemented in Chapter 10, but makes that functionality available to any program as a control — as easy to use as a button.

Begin by creating a new Windows Control Library project in Visual Studio .NET in your language of choice. Call it ClockFaceControl. When you first create the project, you'll be put into the design mode. Right-click on the form and choose View Code. Change the name of the source file from UserControl1.cs or .vb to ClockFaceControl.cs or .vb

Next, change the name of the class from UserControl1 to ClockFaceCtrl, and change the base class from UserControl to Control.

image with no caption

public class ClockFaceCtrl : System.Windows.Forms.Control

Public Class ClockFaceCtrl ...

Get Programming .NET Windows Applications 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.