Web Design that taps into the haromny and vision of your dreams.

Creating Controls for Windows Forms and C#

Creating Windows form controls in c#

Written By on in C#

1,106 words, estimated reading time 6 minutes.

Just like ASP.Net, Windows forms allow the creation of custom controls to extend or enhance existing controls or to create brand new functionality.

Windows Forms Applications Series
  1. Basics of C# Windows Forms Applications
  2. Menus, Popups and Toolbars in .Net Forms and C#
  3. Using Common Dialogue Boxes in C#
  4. List Boxes and Tree Views in C#
  5. List Box Data Binding in C# Windows Forms Application
  6. Using Multiple Forms in C# Applications with MDI
  7. Creating Controls for Windows Forms and C#
  8. Saving User Preferences and Settings within your C# Application

Like ASP.Net, there are different types of custom control in WinForms, some with a designer to add controls (User Control or Composite Control) and others that exist purely in C# (Custom Control) and allow greater freedom in drawing and graphics. You can also create a normal C# class and create inherited controls.

There are many reasons why you may want to extend an existing control. Maybe you need to change the default properties, override the Paint method, add validation events by default. In this tutorial, I will show you how to extend some of the basic controls and extend their functionality.

Extending a Button control

The simplest control to look at is the button control. I'm going to create a new control inherited from a button and I'm going to change a few of the default properties. The reason for doing this is so that all buttons in the application can have the same class and set of properties. If a change needs to be made, a quick modification to the class changes all the buttons in the project. By contrast, if you added the base button control and changed all the properties manually, you would have to go through all the forms in the application and update each button manually.

I used this technique while developing a touchscreen interface. I needed each button to be larger and have a different colour scheme but didn't want to apply the properties to all of the buttons individually. All you need to do is add this control to the form instead of the base button.

To create an inherited control, simply create a new C# class file with a meaningful name and set the class to inherit from the base class, as shown below.

using System;
using System.Windows.Forms;
using System.Drawing;
 
/// <summary>
/// Summary description for TouchscreenButton
/// </summary>
public class TouchscreenButton : Button
{
    public TouchscreenButton()
    {
        this.Width = 100;
        this.Height = 75;
        this.FlatStyle = FlatStyle.Flat;
        this.Cursor = Cursors.Hand;
        this.ForeColor = Color.Black;
        this.BackColor = Color.White;
        this.FlatAppearance.BorderSize = 2;
        this.FlatAppearance.BorderColor = Color.Navy;
    }
}
 

When you add this class and build the project, you will see a new section in the toolbox with the name of your project, and within that an entry for a TouchscreenButton. We'll have a look at the toolbox and options later in this tutorial.

Each time you add a TouchscreenButton to the form, it will have the same default properties as specified above. This is incredibly handy if you are using multiple controls on multiple forms.

Creating Custom Controls for Windows Forms
Creating Custom Controls for Windows Forms

You can also instantiate controls and add them to a form with code and you need not set all the properties.

TouchscreenButton tbtnMyButton = new TouchscreenButton();
placeHolder1.Controls.Add(tbtnMyButton);

You can use this method to override or extend methods, add additional properties or change the behaviour of an existing control.

User Controls

User controls allow you to use the designer to create a composite control (a control made up from other controls). For example, you can add a textbox and a button to the same control and add this new control to a form to save time and effort. This new control handles the logic rather than the form so it aids in scalability and reusability.

To create a new user control, add a new item to the project and select User Control.

I'm going to create a control that will handle file browsing, and simulate a process. This will have a textbox for the filename, a button to select a file, a button to process the file and a progress bar for a simulated process. Using the designer and creating the code behind is just like designing a form so I won't go through this process. You can download the code at the end of this article.

Creating Controls for Windows Forms
Creating Controls for Windows Forms

When using this control in an application, all you need to do is to add the control from the toolbox. All the boxes, buttons and logic will be handled already and your application does not need to do anything. If you choose to add some events to the user control (validate filename, or delegate the process method) your client application can simply subscribe to the events as it would any other control.

Creating Controls for Windows Forms
Creating Controls for Windows Forms

Custom Controls

The final control type is the custom control. This does not have a designer but does let you draw your own graphics. In this part of the tutorial, I am going to create a Smiley control that displays a smiley face.

You can create a custom control by adding a new file to your project and selecting Custom Control.

The OnPaint() method is used to draw shapes using the PaintEventArgs.Graphics property. In a more realistic environment you would use this to draw graphs or charts, but for this example, I'll draw a smiley.

The code behind looks like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace WindowsApplication1
{
    public partial class Smiley : Control
    {
        public Smiley()
        {
            InitializeComponent();
        }
 
        protected override void OnPaint(PaintEventArgs pe)
        {
            // Draw a basic smiley face
            pe.Graphics.FillEllipse(Brushes.Yellow, 0,0,this.Width-1, this.Height-1); // Face
            pe.Graphics.FillEllipse(Brushes.Black, (this.Width / 4), (this.Height / 4), (this.Width / 6), (this.Height / 6)); // Left Eye
            pe.Graphics.FillEllipse(Brushes.Black, this.Width - (this.Width / 3)-10, (this.Height / 4), (this.Width / 6), (this.Height / 6)); // Right Eye
            pe.Graphics.DrawArc(Pens.Black, (this.Width / 4), (this.Height / 2), (this.Width / 2), (this.Height / 4), 0, 180); // Mouth
 
            // Calling the base class OnPaint
            base.OnPaint(pe);
        }
    }
}
 

It's only basic, but it shows how to draw using the graphics and what's more it will scale when the control is resized. This is what it looks like on the form:

Creating Controls for Windows Forms
Creating Controls for Windows Forms

That's just about it for the controls. We've seen how to create inherited controls, user controls and custom controls.

Adding Properties

You can add a property to the property window for your control simply by creating a public property.

private string _smileyName;
public string SmileyName
{
    get { return _smileyName; }
    set { _smileyName = value; }
}

You can use this method for any of the basic data types such as int, string, bool, decimal and so on. You can also use this to create an advanced data type such as a enum as shown in the example below.

Control Properties
Control Properties
public enum SampleColours
{
    Red,
    Green,
    Blue,
    Yellow
}
 
private SampleColours _smileyColor;
public SampleColours SmileyColor
{
    get { return _smileyColor; }
    set { _smileyColor = value; }
}
 

This will be shown as a drop down list containing the items in the enum.

Control Properties
Control Properties

Last updated on: Wednesday 21st June 2017

 

Comments
Maimoona ch

Maimoona ch

can u help how can we add smily face in richtextbox by click on smiely button app(like yahoo email app ) in c#

Reply to Maimoona ch
Pete

Pete

Very much appreciate all your tutorials. Very concise with exactly the right amount of detail. Thank you very much!

Reply to Pete
LLB

LLB

I have a similar UserControl application. it works quite good when I debug it but if I put it in a form application and change a property, I take "Object reference not set to an instance of an object" error although I defined the property 'public'?

Reply to LLB
jt

jt

Excellent Article!

I do have a question...

I was playing with adding another smiley (green) dynamically, that would draw to the right of the existing yellow smiley. It doesn't seem to do what I had expected.

Here's the Form1.cs code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
Smiley smiley;

public Form1()
{
InitializeComponent();

smiley = new Smiley(10,10);

smiley.Location = new System.Drawing.Point(145, 145);
smiley.Name = "smiley2";
smiley.Size = new System.Drawing.Size(120, 120);
smiley.SmileyColor = WindowsApplication1.Smiley.SampleColours.Green;
smiley.SmileyName = null;
smiley.TabIndex = 5;
smiley.Text = "smiley2";

smiley.Visible = true;

}
}
}

Thanks,

jt

Reply to jt
riper

riper

Excellent article! Thanks for describing something rather complex in so few words! :)

Reply to riper

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me