Creating a Custom Control in Winforms - Part 1

Creating the Square control

Creating a custom control in windows forms is very simple – there are a few gotchas along the way – so I thought I’d make a sample control called “Square” to walk through it. The square will obviously have sizing restrictions, but will also do some simple custom drawing.

 

Making sure we’re the right size

I want the size of my control to default to something, well, square shaped when dropped onto the form. Therefore I want to control the initial size to be equal in width and height. There are a couple of ways to do this.

 

In the constructor, I could say

   public class Square : Control {

        public Square() {

  this.Size = new Size(100,100);

        }

   }

However when I expand InitializeComponent, I see the size written out at 100,100. While this is correct, in general we try not to write things that are already the default value.

 

Most controls achieve this by overriding the DefaultSize property. The magic of the DefaultSize property is executed in the constructor of the base class Control – that is – it sets up the default by saying:

       public Control () {

       this.Size = this.DefaultSize;

       }

 

MSDN suggests that for perf reasons, overriding is the best way to handle setting up the default. It’s also there for the designer. If the Size matches the DefaultSize, the default implementation of ShouldSerializeSize returns false – thus preventing it from being written to IntializeComponent More about ShouldSerialize method here.

 

Changing around our code:

 

   public class Square : Control {

        public Square() {

        }

        protected override Size DefaultSize {

            get { return new Size(100,100); }

        }            

   }

….creates a 100 by 100 square when dropped onto the design surface.

 

Next time:

We'll try adding a splash of color by overriding OnPaint.