TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

How To Create Custom Control in C# Windows Forms

c# custom button - Custom controls are specialized controls in .NET derived from Control class.This article explains step by step process of creating a custom control in C# Winform application.

Custom controls are specialized controls in .NET derived from Control class.

c# custom button Control

In this article I will discuss the step by step process of creating a custom control in C# winform application.The example is a Specialized C# button control which changes its look and feel when mouse hover it.

If not active the button will appear as shown in the below sccreen shot. 

The Innovators: How a Group of Inventors, Hackers, Geniuses and Geeks Created the Digital Revolution- A must Read

When you hover mouse over the button(foucs the button) the look and feel of the button changes as below and the cursor type also changes as Hand type.

 

Now lets see the steps involved in creating this special button control.

1.   Launch Visual studio and Create a Windows control library project Name it as SpecialButton. By default it will create a Usercontrol class.Delete the       same since we are not creating a user control here.

2. Now right click on project and Select Add New item.Select Custom Control from the list.Name the control as SpecialButton(you can choose whatever    name you want).

3. Go to source code window and add the following code.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace SpecialButton 
{
    public partial class SpecialButton : Button
    {
        public SpecialButton()
        {
            InitializeComponent();
            //Set default property values for the button during start up
            SetNormalValues();
        }
        /// <summary>
        /// To Set button properties when not active.i.e when button not in focus.
        /// </summary>
        private void SetNormalValues()
        {
            this.Font = new Font("Verdana", 8F, FontStyle.Bold);
            this.BackColor = Color.Gray;
            this.ForeColor = Color.White;
            this.Margin = new Padding(4, 1, 4, 1);
            this.Padding = new Padding(4);
            this.MinimumSize = new Size(150, 35);
            this.Cursor = Cursors.Arrow;
        }

        /// <summary>
        /// Set attributes to highlight button when it is under focus/active.
        /// Change the cursor also as Hand type
        /// </summary>
        private void SetValuesOnFocus()
        {
            //Increase the font size and colors on focus
            this.Font = new Font("Verdana", 10F, FontStyle.Bold);
            this.BackColor = Color.Green;
            this.ForeColor = Color.White; 
            //Set the cursor to Hand type
            this.Cursor = Cursors.Hand;
        }
        

        /// <summary>
        /// Default handler.Nothing to do here since we don't need to repaint the button.
        /// </summary>
        /// <param name="pe"></param>
        protected override void OnPaint(PaintEventArgs pe)
        {
            base.OnPaint(pe);
        }

        /// <summary>
        /// Event handler which call SetValuesOnFocus() method to give apecial
        /// effect to button while active
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseHover(EventArgs e)
        {
            base.OnMouseHover(e);
            SetValuesOnFocus();
        }

        /// <summary>
        /// Event handler which call SetNormalValues() method to set back the button
        /// to normal state
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseLeave(EventArgs e)
        {
            base.OnMouseLeave(e);
            SetNormalValues();
        }       
    }

}

 4. Build the solution successfully.Your custom control library is ready now. Feel free to customize the code if you want more affect.For eaxample the above code works on mouse events only. For getting it work on tab key you need to use events like,

protected override void OnEnter(EventArgs e)
        {
            base.OnEnter(e);
            SetValuesOnFocus();
        }

        protected override void OnLeave(EventArgs e)
        {
            base.OnLeave(e);
            SetNormalValues();
        }

 

For the time being, we will concentrate on the above mentioned code with mouse events to undestand the basics of creating custom control in C#. 

Howto consume the custom control in C#

1. Create a normal windows form project. Reference the above created SpecialButton Control library dll.

2. You can see the SpecialButton displayed in the toolbar top left if the project inside the same solution as SpecialButton control library.

3. If  the control library is independent solution and Test project is part of another solution then you need to Add the control to the toolbox.For that go to the bottom of ToolBox and Right click. Select Choose Items from the context menu.Now Go to .NET Framework Components tab.Click the Browse button and choose your library(SpecialButton) from the bin folder.

4. Now you can see the custom control listed in the bottom of tool box as below.

 

  1. Drag & drop the SpecialButton to your form and set the button name and Text.I named the button as btnSpecialButton and gave caption Test as Test Button. In the button click event write the following code to ensure button work as expected.
private void btnSpecialButton_Click(object sender, EventArgs e)
 {
     MessageBox.Show("C# Custom button click test");
}

Run your winform project Test the button.On mouse enter to button you get the highlighted effect with Hand cursor.On Click you get the messagebox.On mouse leave button go back to default state.

 

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

TechyMedia | A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

What is Internet of Things ?

Few people have not heard about the development of the Internet of Things. This is something that is said to determine the future. The Internet of Things is an arrangement of interrelated figuring gadgets, mechanical and advanced machines, articles, creatures or individuals that are given one of a kind identifiers and the capacity to exchange information over a system without obliging human-to-human or human-to-PC cooperation. A thing, in the Internet of Things, can be a man with a heart screen embed, a homestead creature with a bio chip transponder, a vehicles that has worked in sensors to alarm the driver when tire weight is low, or whatever other common or man-made item that can be relegate [More]

Namespaces In C#

Namespace in C# is logical grouping of related classes.Classes which are related can be logically grouped in named collection called namespace. So a namespace will give unique fully qualified identifier to a class,which avoids name conflicts.There is no physical mapping of namespaces in C#.That is classes with same namespace can scatter across folders,not necessarily be in same folder/project. [More]

C# 6.0 Features | What is new in C# 6.0

C# 6.0 if the latest version of C# language which ships with Visual Studio 2015. C#.NET 6.0 comes with a set of new advanced features which are mainly targeted to improve the developer experience.A new compiler technology named "Roslyn" also introduced this time which is an open source under the Apache 2 licence.With Roslyn compiler efficiency is improved and feature integration to languages are made ready. Accordingly in C# version 6.0 Microsoft has added number of new features. [More]

Deserialize XML to object c#

Deserialize XML to object c# -Reading the data stored in a XML file to a class object.Deserialize method from the XmlSerializer class is used for reading/deserializing the XML file data to the class object.Sample Method to Deserialize the xml file.Method which creates an object and deserialize the xml data to the object .
Deserialize XML to object c# -Reading the data stored in a XML file to a class object.Deserialize method from the XmlSerializer class is used for reading/deserializing the XML file data to the class object.Sample Method to Deserialize the xml file.Method which creates an object and deserialize the xml data to the object . [More]

Write Class Data to an XML File in C# | serialize c# xml

XmlSerializer class is used for writing/storing the class object data to an XML file. This is Serialization of class object. C# - Write Class Data to an XML File code sample. XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(objectToSerialize.GetType());
XmlSerializer class is used for writing/storing the class object data to an XML file.
This is Serialization of class object. C# - Write Class Data to an XML File code sample. XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(objectToSerialize.GetType()); [More]

Read XML File in C# - Read Content From XML File

Example for the XMLTextReader class to read the xml element names. Read XML Content From a File- C#.
Example for the XMLTextReader class to read the xml element names. Read XML Content From a File- C#. [More]

Browse Network using FolderBrowserDialog C# Control

.NET How to Browse Network using FolderBrowserDialog Control: Type folderBrowserType = folderBrowserDialog1.GetType();System.Reflection.FieldInfofieldInfo = folderBrowserType .GetField(&quot;rootFolder&quot;,BindingFlags.NonPublic | BindingFlags.Instance); fieldInfo .SetValue(folderBrowserDialog1, (Environment.SpecialFolder)18);
.NET How to Browse Network using FolderBrowserDialog Control: Type folderBrowserType = folderBrowserDialog1.GetType();System.Reflection.FieldInfofieldInfo = folderBrowserType .GetField("rootFolder",BindingFlags.NonPublic | BindingFlags.Instance);
fieldInfo .SetValue(folderBrowserDialog1, (Environment.SpecialFolder)18); [More]

Writing to File In C#

File IO handling is a common activity in all programming languages.File IO operations such as Read from a File and Write to file are very easy to handle in C#.In this example you will see some sample Write to File operations in C#. Here I am explaining of writing to a text file.For write to file in C# we can use StreamWriter class.StreamWriter class has method WriteLine which can be used for writing strings to the text file. [More]

How to handle File access IO exception

File accessing file you may get IO exception was unhandled, the process cannot access the file because it is being used by another process.The reason fot this exception may be lke,File you are trying to open not even exist, File is in process by another thread,File is already kept open etc.How to handle this exception.
File accessing file you may get IO exception was unhandled, the process cannot access the file because it is being used by another process.The reason fot this exception may be lke,File you are trying to open not even exist, File is in process by another thread,File is already kept open etc.How to handle this exception. [More]

WCF Bindings | What are Different Bindings Supported by WCF?

Basic http binding is mainly meant for backward compatibility so that older older .NET version applications such as asmx web services can consume this binding based service. BasicHttpBinging no security as such by default.That means data is sent as plain text over http. Basic Http Binding not support WS-* specifications and hence this binding is not secure.No transaction support and not suitable for reliable messaging.Message transport is SOAP 1.1 based. [More]