Introduction to Designers

Getting Started

As this article is only meant to be a brief introduction to designers, we won't make anything terribly complicated. Before we can make a designer we need a control to design, so we'll create a simple usercontrol that draws an ellipse in its client area.

To create a custom designer for a control you will either inherit from ControlDesigner or ParentControlDesigner, depending on whether you want users to be able to place child controls in your control. All we need for this article is to inherit from ControlDesigner. You will need to add an assembly reference to System.Design.dll to see these classes. To associate your designer class with your control, you use the DesignerAttribute class:

[VB]
Imports System.Windows.Forms.Design
Imports System.ComponentModel
<Designer(GetType(MyControlDesigner))> _
Public Class UserControl1
    Inherits System.Windows.Forms.UserControl
    Public Sub New()
        MyBase.New()
        SetStyle(ControlStyles.ResizeRedraw, True)
        SetStyle(ControlStyles.AllPaintingInWmPaint, True)
        SetStyle(ControlStyles.DoubleBuffer, True)
    End Sub
    Private Sub UserControl1_Paint(ByVal sender As Object, _
    ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
        e.Graphics.DrawEllipse(Pens.Red, ClientRectangle)
    End Sub
End Class
Friend Class MyControlDesigner
    Inherits ControlDesigner
End Class

[C#]
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace CSharpTest
{
    [Designer(typeof(MyControlDesigner))]
    public class UserControl1 : System.Windows.Forms.UserControl
    {
        public UserControl1()
        {
            SetStyle(ControlStyles.ResizeRedraw, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.DoubleBuffer, true);
            this.Paint += new PaintEventHandler(UserControl1_Paint);
        }
        private void UserControl1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawEllipse(Pens.Red, ClientRectangle);
        }
    }
    internal class MyControlDesigner : System.Windows.Forms.Design.ControlDesigner
    {
    }
}

In the Form designer, you should see the UserControl you just created in the toolbox, and you can drag it on to the form like you would any other control. Although our designer class doesn't do anything yet, the instance on the form is using it.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Memory is like an orgasm. It's a lot better if you don't have to fake it.” - Seymour Cray