Click here to Skip to main content
15,867,594 members
Articles / Programming Languages / C#
Article

Your first C# control

Rate me:
Please Sign up or sign in to vote.
4.61/5 (40 votes)
20 Nov 2000 682.9K   3.9K   122   44
A very simple introduction to writing your first .NET control
  • Download source files - 1 Kb
  • Sample Image - first_control.gif

    Introduction

    This is an extremely simple introduction to creating a control, adding methods and properties, and adding event handlers.

    There are two types of components, Visible components (such as a edit box, list control) and non-visible (such as timers, communication, and data access).

    This article will concentrate on the creation of a visible component, however the concepts do apply to non visible controls as well.

    Visible Components

    A visible component is any class derived from either System.WinForms.Control or System.WinForms.RichControl.

    Here is the minimum code to produce the most basic visible control that functions correctly (but doesn't actually do anything).

    C#
    //specify the namespace in which the control resides
    namespace Test.Control
    {
          //specify the name spaces of other classes that are commonly referenced
          using System.WinForms;
          
          //the control definition and implementation
          public class MyControl : System.WinForms.RichControl 
          {
          }
    }

    Now, if you ask me, this is a lot more straight forward than any OCX control I have ever written (ATL or not).

    The control above, since it is derived from RichControl, contains quite a bit of stock functionality including: stock properties, stock events, layout management, the ability to act as a full control container (for child controls), and more. In other words, just start writing in your business logic, all of the grunt work is taken care of.

    Since the control has no paint routine - yet - it will only erase its background to its parents background color, so it is not too useful at this point. Adding a simple paint routine is also quite simple.

    C#
    using System.Drawing;
    
    protected override void OnPaint(PaintEventArgs pe)
    {
        SolidBrush b = new SolidBrush(this.BackColor);
        pe.Graphics.FillRectangle(b,this.ClientRectangle);
    }     

    The code above will paint the control using its BackColor property. So if you add this control to a form now and modify its BackColor propery via the property sheet the control's color will now change as well.

    Notice that using System.Drawing; has been added. This allows classes such as SolidBrush to be used without specifying the entire namespace (System.Drawing.SolidBrush).

    Adding a property

    Adding a read/write or read only property to a control is also quite straight forward. In this example I am going to add a set of gradient color properties to the control. Below I am only going to show one of the properties, since the other is a mirror copy of the first, except for the variable name.

    C#
    private System.Drawing.Color gradColor1;
    
    public System.Drawing.Color Gradient1
    {
        set
        {
            this.gradColor1 = value;    
        }
        get
        {
            return this.gradColor1;
        }
    }

    So, first I must add a data member to hold the properties value. Since the property is a color it will be of type System.Drawing.Color. Since using System.Drawing; has been added the variable can also be declared as just Color.

    Next the declaration for the Gradient1 property is made. The start of the declaration looks similar to a function declaration (access modifier, return type, and name). Although the property itself is not a function it can contain two special functions nested within it: set and get. To make a read/write property both set and get must be implemented. For a read-only property just implement get. Even though the set function does not have a parameter list, it does get passed a special parameter called value. The type of the Value parameter will always be the same type as the property itself.

    Since properties are set and retrieved indirectly (which is quite different from reading and writing to data members), other code can be added to the set and get functions. For instance if a property is a calculated value, the calculation can be performed within the get itself. During a set it is possible to set flags or cause the control to refresh itself, etc.

    To make a control easy to use during design time, many controls group their properties and have help strings that display when the property is selected in the property browser. This can also be easily accomplished through the use of attributes. Attributes are special objects that are added above the declaration of a class, function, enum or property, and are delimited by ‘[‘ and ‘]’.

    C#
    [
        Category("Gradient"),
        Description("First Gradient Color")
    ]
    public System.Drawing.Color Gradient1
    {
        set
        {
            this.gradColor1 = value;    
        }
        get
        {
            return this.gradColor1;
        }
    }

    The attributes above cause this property to show up in a Gradient property group and will display "First Gradient Color" as a help string at the bottom of the property browser when selected.

    Adding a method

    Adding a method is the same as adding any other function. In fact a function and method are essentially the same in the .Net world. If you do not want the function exposed to the outside just make sure its access modifier is set to protected or private. This is not to say that all your public functions can be used by anyone, you have quite a bit of control over the use of your functions … but that is another topic.

    C#
    public void StartRotation(bool state)
    {
        ...
    }

    In this example the function StartRotation will be added, which will rotate the angle of the gradient based on a timer.

    C#
    private System.Timers.Timer rotateTimer = null;
    
    public void StartRotation(bool state)
    {
        rotateTimer = new System.Timers.Timer();
        rotateTimer.Tick += new EventHandler(OnTimedEvent);
        rotateTimer.Interval= 500; 
        rotateTimer.Enabled = true;
    }  
        
    public void OnTimedEvent(object source, EventArgs e)
    {
        gradAngle += 10; 
        if(gradAngle > = 360)
        {
            gradAngle = 0;
        }
        this.Refresh();
    }

    Since the timer class fires an event, you will notice the code required to use an event is quite basic, however I will explain how events work later on.

    When the event fires it will call the specified function, this is where the angle is updated and a Refresh is requested.

    Using and Adding Events

    In the previous section code was added that used a timer event.

    C#
    rotateTimer.Tick += new EventHandler(OnTimedEvent);

    The Timer class has an event member called Tick that handles a list of event listeners. Since an event can have more than one listener the += is used to assign the event.

    So to tell the timer to call the event handler OnTimedEvent just create a new event handler, pass in the function name into the constructor and assign that to the Timers event list. Any number of event handlers can be added to a single event. Note, the order in which the handlers are called is not defined.

    To create your own event here is what to do.

    First declare the interface of the event (its required parameters and return type), then make an instance of this type. Note the use of delegate.

    public delegate void angleChange();
    public event angleChange OnAngleChange;

    The code above adds an event list OnAngleChange that can be used to add an event in the following manner

    C#
    MyControl ctrl = new MyControl();
    ctrl.OnAngleChange += new MyControl.angleChange(OnMyEvent);
    
    public void OnMyEvent()
    {
        MessageBox.Show("Event Fired");
    }

    To actually fire an event you need to first check that your event is non-null, and then fire the event using the following:

    C#
    if (OnAngleChange != null)
    {
       OnAngleChange();
    }
    

    Simple! So now you have your first control that has methods, properties and events.

    The complete source code is below:

    C#
    //specify the namespace in which the control resides
    namespace Test.Control
    {
        //specify the name spaces of other classes that are commonly referenced
        using System;
        using System.Collections;
        using System.Core;
        using System.ComponentModel;
        using System.Drawing;
        using System.Drawing.Drawing2D;
        using System.Data;
        using System.WinForms;
        using System.Timers;
    
        
        //the control definition and implementation
        public class MyControl : System.WinForms.RichControl
        {
            private System.Drawing.Color gradColor1;
            private System.Drawing.Color gradColor2;
            private int gradAngle = 0;
    
            private System.Timers.Timer rotateTimer = null;
    
            public delegate void angleChange();
            public event angleChange OnAngleChange;
    
            private void InitializeComponent ()
            {
            }
        
            public MyControl()
            {
                InitializeComponent();
    
            }
    
            protected override void OnPaint(PaintEventArgs pe)
            {
                  LinearGradientBrush b = new LinearGradientBrush(this.ClientRectangle,
                    gradColor1, gradColor2,gradAngle,false);
                  
                  pe.Graphics.FillRectangle(b,this.ClientRectangle);
            }    
    
            public void StartRotation(bool state)
            {
                
                rotateTimer = new System.Timers.Timer();
                rotateTimer.Tick += new EventHandler(OnTimedEvent);
                // Set the Interval to 5 seconds.
                rotateTimer.Interval=500;
                rotateTimer.Enabled=true;
    
            }
    
            public void OnTimedEvent(object source, EventArgs e)
            {
                gradAngle += 10;
                if(gradAngle >= 360)
                {
                    gradAngle = 0;
                }
                this.Refresh();
    
                if(OnAngleChange != null)
                {
                    OnAngleChange();
                }
            }
    
    
            [
                Category("Gradient"),
                Description("First Gradient Color")
            ]
            public System.Drawing.Color Gradient1
            {
                set
                {
                    this.gradColor1 = value;    
                }
                get
                {
                    return this.gradColor1;
                }
            }
    
            [
                Category("Gradient"),
                Description("Second Gradient Color")
            ]
            public System.Drawing.Color Gradient2
            {
                set
                {
                    this.gradColor2 = value;    
                }
                get
                {
                    return this.gradColor2;
                }
            }
        }
    }

    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


    Written By
    Web Developer
    Canada Canada
    Troy Marchand is VP of Product Development at Dundas Software.

    Comments and Discussions

     
    GeneralMy vote of 5 Pin
    Member 80364469-Jul-11 7:19
    Member 80364469-Jul-11 7:19 
    GeneralControl Tasks Context Menu Pin
    kjward19-Apr-10 11:04
    kjward19-Apr-10 11:04 
    Generalocx Pin
    salam ellayan22-Sep-08 21:49
    salam ellayan22-Sep-08 21:49 
    hi
    i need pocket pc OCX writtten in C# as soon as possible plz ...........
    GeneralVery nice article! Pin
    radialronnie7-Jun-08 7:56
    radialronnie7-Jun-08 7:56 
    GeneralCustom Button in Windown CE Pin
    lanbuithe30-Jan-07 23:08
    lanbuithe30-Jan-07 23:08 
    GeneralGJ Pin
    [V]GreyWolf28-Jun-06 5:44
    [V]GreyWolf28-Jun-06 5:44 
    Generaluse System.Windows.Forms.Timer instead Pin
    myselfandi12-Sep-05 2:14
    myselfandi12-Sep-05 2:14 
    GeneralProperty List Pin
    Avhijit2-Nov-04 19:20
    Avhijit2-Nov-04 19:20 
    GeneralrotateTimer.Tick?? - 'Tick' doesn't exist Pin
    TeisDraiby6-Apr-04 12:15
    TeisDraiby6-Apr-04 12:15 
    GeneralRe: rotateTimer.Tick?? - 'Tick' doesn't exist Pin
    TeisDraiby7-Apr-04 2:21
    TeisDraiby7-Apr-04 2:21 
    GeneralRe: rotateTimer.Tick?? - 'Tick' doesn't exist Pin
    vinicio3220-Jun-06 5:56
    vinicio3220-Jun-06 5:56 
    Questionmissing some basic information ? Pin
    M i s t e r L i s t e r9-Jan-04 10:29
    M i s t e r L i s t e r9-Jan-04 10:29 
    AnswerRe: missing some basic information ? Pin
    MoustafaS2-May-05 9:46
    MoustafaS2-May-05 9:46 
    Generalhelp to create user control which will arrange controls in polygonal shape Pin
    Shailaja13-Nov-03 0:37
    Shailaja13-Nov-03 0:37 
    GeneralIcons Pin
    WillemM25-Mar-03 5:58
    WillemM25-Mar-03 5:58 
    GeneralRe: Icons Pin
    Kant7-May-03 16:58
    Kant7-May-03 16:58 
    GeneralRe: Icons Pin
    WillemM7-May-03 19:26
    WillemM7-May-03 19:26 
    QuestionRichControl? Pin
    khimmy16-Feb-03 20:00
    khimmy16-Feb-03 20:00 
    AnswerRe: RichControl? Pin
    Anonymous17-Mar-03 20:08
    Anonymous17-Mar-03 20:08 
    AnswerRe: RichControl? Pin
    faredu18-Mar-03 16:12
    faredu18-Mar-03 16:12 
    Generalhelp me,vertically input text Pin
    jirigala3-Dec-02 19:18
    jirigala3-Dec-02 19:18 
    Generalif i no use System.Drawing.Color Pin
    zjwuweim31-Aug-02 17:11
    zjwuweim31-Aug-02 17:11 
    Generalnamespace name 'WinForm' Pin
    HmendezM2-Oct-01 8:17
    HmendezM2-Oct-01 8:17 
    GeneralRe: namespace name 'WinForm' Pin
    Jamie Nordmeyer14-Jan-02 8:04
    Jamie Nordmeyer14-Jan-02 8:04 
    GeneralRe: namespace name 'WinForm' Pin
    Mazdak11-Feb-02 0:30
    Mazdak11-Feb-02 0:30 

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

    Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.