Click here to Skip to main content
Click here to Skip to main content

Writing your Custom Control: step by step

By , 31 Mar 2002
 

Sample Image - cuteButton.jpg

Introduction

This is a short and simple demonstration of .NET framework's capability of creating custom controls.

Here I'm going to make a custom control and then, test my control in a Windows application. I have implemented some custom properties for my control, so you can learn how it is done in C#.

Building the Control

  1. Open the Visual Studio and start a new project. Your project must be based on the Windows Control Library template. Call your project ctlCuteButton and click OK.

  2. Once you have your project open, delete the UserControl from the project. Just remove it because the 'User Control' is not exactly what we need here.

  3. Now go to the 'Project' menu: Project->Add User Control... and select the Custom Control template there. 'Custom Control' is what we need in this case. You may call it cuteButton. Now click OK. A new Custom control has been added to your project.

  4. The first thing we must do here is to change the base class of the cuteButton:

    Override the following line:

    public class cuteButton : System.Windows.Forms.Control

    by this one:

    public class cuteButton : System.Windows.Forms.Button

    Now your control is based on the System.Windows.Forms.Button class.

  5. Now let's create some custom properties for our control. This is done by inserting the following code inside the cuteButton class:

    private Color m_color1 = Color.LightGreen;  //first color
    private Color m_color2 = Color.DarkBlue;   // second color
    private int m_color1Transparent = 64; // transparency degree 
                                          // (applies to the 1st color)
    private int m_color2Transparent = 64; // transparency degree 
                                          //  (applies to the 2nd color)
    
    public Color cuteColor1
    {
        get { return m_color1; }
        set { m_color1 = value; Invalidate(); }
    }
    
    public Color cuteColor2
    {
        get { return m_color2; }
        set { m_color2 = value; Invalidate(); }
    }
    
    public int cuteTransparent1
    {
        get { return m_color1Transparent; }
        set { m_color1Transparent = value; Invalidate(); }
    }
    
    public int cuteTransparent2
    {
        get { return m_color2Transparent; }
        set { m_color2Transparent = value; Invalidate(); }
    }

    The Invalidate() methoid is used to refresh the design view and all controls inside (the tip from Tom Welch).

  6. And the last thing to do before compiling our control is to override the Paint event. So let's do it:

    // Calling the base class OnPaint
    base.OnPaint(pe);
    // Create two semi-transparent colors
    Color c1 = Color.FromArgb(m_color1Transparent , m_color1);
    Color c2 = Color.FromArgb(m_color2Transparent , m_color2);
    Brush b = new System.Drawing.Drawing2D.LinearGradientBrush(ClientRectangle, 
                                                               c1, c2, 10);
    pe.Graphics.FillRectangle (b, ClientRectangle);
    b.Dispose();
  7. Now you may compile the control by pressing <Ctrl>+<Shift>+<B>.

Here is the complete contents of cuteButton.cs file (just in case…):

COMPLETE CODE:

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


namespace ctlCuteButton
{
    /// <summary>
    /// Summary description for cuteButton.
    /// </summary>

    public class cuteButton : System.Windows.Forms.Button
    {
    private Color m_color1 = Color.LightGreen; // first color
    private Color m_color2 = Color.DarkBlue;  // second color
    private int m_color1Transparent = 64; // transparency degree 
                                             // (applies to the 1st color)
    private int m_color2Transparent = 64; // transparency degree 
                                          //  (applies to the 2nd color)

    public Color cuteColor1
    {
        get { return m_color1; }
        set { m_color1 = value; Invalidate(); }
    }

    public Color cuteColor2
    {
        get { return m_color2; }
        set { m_color2 = value; Invalidate(); }
    }

    public int cuteTransparent1
    {
        get { return m_color1Transparent; }
        set { m_color1Transparent = value; Invalidate(); }
    }

    public int cuteTransparent2
    {
        get { return m_color2Transparent; }
        set { m_color2Transparent = value; Invalidate(); }
    }


    public cuteButton()
    {
    }


    protected override void OnPaint(PaintEventArgs pe)
    {
        // Calling the base class OnPaint
        base.OnPaint(pe);
        // Create two semi-transparent colors
        Color c1 = Color.FromArgb
            (m_color1Transparent , m_color1);
        Color c2 = Color.FromArgb
            (m_color2Transparent , m_color2);
        Brush b = new System.Drawing.Drawing2D.LinearGradientBrush
            (ClientRectangle, c1, c2, 10);
        pe.Graphics.FillRectangle (b, ClientRectangle);
        b.Dispose();
    }
}
}

Testing the Control

  1. Open a new instance of the VS .NET. Create a new project choosing the Windows Application template.

  2. From a new Windows Forms project, we can add the compiled custom control to the toolbox. I do this by right-clicking the toolbox, selecting Customize Toolbox, and from the .NET Framework Components tab, clicking Browse and locating the Control Library DLL # (in our case, ctlCuteButton\bin\debug\cuteButton.dll). The component cuteButton will then appear in the Toolbox.

    You can play a bit changing it’s properties (cuteColor1, cuteColor2, cuteTransparent1, cuteTransparent2).

That’s all so far about building and using custom controls.

Good Luck.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Alexandr_K
Web Developer
Canada Canada
Member
Years of programming...

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberbatime3 Dec '12 - 0:07 
cool man
QuestionJust a questionmemberGrumbscut27 Nov '12 - 22:12 
Hi nice tutorial!
 
I managed to transform it for VB. I tried it and everthing works well. My first control Smile | :) !
But if i set tranparency to 255 for each of the colors the label text for the button is not readable. How can i set the label text on top of the colors so it would be readable in any setting of the transparency?
AnswerRe: Just a questionmemberGrumbscut28 Nov '12 - 2:26 
Did a little workaround to fix the issue.
implemented new private properties m_text and m_textAlignment
and updated the onpaint with DrawString(m_text...) after FillRectAngle
Question5 starsmemberIsuru Nanayakkara21 Nov '12 - 0:38 
Very nice and easy to comprehend article. It was my first time going at creating a custom control . I always thought it was a difficult task but this made me look into playing with it even further. Thanks Smile | :)
a geek by day, a freak by night

GeneralMy vote of 5memberamish kumar2 Nov '12 - 21:03 
Good Article to learn Smile | :)
GeneralMy vote of 5memberavidela17 Oct '12 - 11:48 
Easy to understand and very useful!
SuggestionA very useful easy to understand step by step guide to create custom control in visual studio with snap-shotsmemberKrishanGahlot30 Sep '12 - 18:37 
http://csharpdemos.blogspot.in/2012/09/creating-custom-control-textbox-in.html

Questionexcellencememberdaghune3 Sep '12 - 23:30 
very good very good
Wink | ;)
GeneralMy vote of 2memberdaghune3 Sep '12 - 23:14 
Not Complete
GeneralRe: My vote of 2memberamirmohamad3 Sep '12 - 23:30 
sh*t man this is a complete article in codeproject
GeneralRe: My vote of 2memberdaghune3 Sep '12 - 23:32 
it is not your business baby gaga
shut down youreself before i do that
GeneralRe: My vote of 2memberamirmohamad3 Sep '12 - 23:33 
f*** your ass Suspicious | :suss:
GeneralRe: My vote of 2memberdaghune3 Sep '12 - 23:34 
dahaneto gayidam sag sende lashgush zan jende sagggggggg
kun pashm kuni lashmaste divane
kuniiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
lashiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
shaskeshhhhhhhhhhhhhhhhhhhhhhhh
GeneralArsefuckrmemberbartjuh1027 Dec '12 - 10:03 
Mencuntfucker
Questiongreat articlememberWrangly10 Jan '12 - 22:15 
Great article ! very usefull !! thanks.
QuestionSupermemberMember 84713099 Dec '11 - 2:48 
Superb Work
GeneralMy vote of 5 [modified]memberGuyThiebaut29 Oct '11 - 6:21 
Thanks - exactly what I was looking for +5

modified 29 Oct '11 - 12:30.

GeneralMy vote of 4memberMember 772135016 Apr '11 - 0:50 
Its gud and simple one easy to understand.
GeneralGood JobmemberRockingDownTheHighway9 Feb '11 - 16:36 
Thanks
QuestionIs it PRO version required?memberBogdanJankowski1 Mar '10 - 4:27 
does it just work for VS professional version?
QuestionHow to anchor a custom control?memberChanHwiHwang10 Nov '09 - 17:01 
Hi,
I have just make a custom control and I drag it into a win form.
Everything run well, but when I enlarge the window, the custom control and other normal control just 'move' to the center of the window.
I want all of the controls to enlarge like it container, so I add Anchor to all the control, setting them all anchor top, left, right and bottom. And the worse thing happen. The normal controls overlap on the custom control I make. I think that happened because I had overridden the Paint function of the custom control to draw my own image but I don't know how to solve it. Can you give me some hint for it?
GeneralThanksmemberrutstyle20 Jun '09 - 0:09 
good tutorial Poke tongue | ;-P
AnswerWindows Forms Control Library =~ Windows Control Library, also a partial class errormemberdblanchard17 Mar '09 - 15:00 
In VS 2008 Pro, I couldn't find the Windows Control Library template; from running through this example, the Windows Forms Control Library template seems to be functionally the same.
 
If I'm wrong, or just overlooking something, please correct me.
 
Also, I got a an error in VS 2008 when compiling:
Error 1 Missing partial modifier on declaration of type 'ctlCuteButton.cuteButton'; another partial declaration of this type exists C:\Documents and Settings\...\My Documents\Visual Studio 2008\Projects\...\Project1\ctlCuteButton\ctlCuteButton\cuteButton.cs 12 18 ctlCuteButton
 
Changing to the following fixed it, but I'm too noobian to understand the error:
public partial class cuteButton : System.Windows.Forms.Button
 
modified on Tuesday, March 17, 2009 10:19 PM

General3Ksmemberwhatcsu3 Aug '08 - 13:14 
That is very good...
Thanks...
Smile | :)
GeneralThanksmemberLaurent Cozic2 Aug '08 - 9:10 
Very simple and clear tutorial. Thanks!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 1 Apr 2002
Article Copyright 2002 by Alexandr_K
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid