Specializing an Existing Control

You'll create a customized button class that keeps track of how often it has been clicked. To begin, open a new project in Visual Studio .NET. In the Project Type window, choose your language of choice, and in the Templates window, choose Windows Control Library. Be sure to set an appropriate location, and name the library CountedControl.

Tip

This example is similar to a custom control demonstrated in Programming ASP.NET, but there are significant differences in how custom controls are created for use with Windows Forms.

You are placed in the designer for a user control. That isn't quite what you want (you'll be creating a user control in the next example), but it isn't a problem. Right-click on the form and choose View Code. Modify the class name to CountedButton and the base class from UserControl to Button:

image with no caption

public class CountedButton : System.Windows.Forms.Button

image with no caption

Public Class CountedButton
    Inherits System.Windows.Forms.Button

In C#, you must also modify the constructor so it has the same name as the class:

image with no caption

public CountedButton(  )

While you are at it, change the filename from UserControl1 to CountedButton.cs or CountedButton.vb.

Tip

When you change the ...

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.