Introduction
Simple Custom Controls
Custom controls are control that are created by user when Windows Forms controls do not fulfill their application requirements. Simple custom controls can be created by inheriting the Control class, UserControl class, or any Windows Forms controls. The developer should write the code for the custom control in the OnPaint event of the control. After writing the code, it should be saved with the .cs extension. The code can be complied into an assembly and saved into the application’s directly by executing the following command:
Syntax
csc /t:library/out:<path to your application;s directory>/<name of the assembly that contains the custom control class> /r:System.dll
/r: System.Windows.Form.dll /r: System.Drawing.dll <name of the custom control class file>
Where,
- /t:library, Instructs the compiler that the assembly that is being created is a library and it is cannot be executed.
- /out : Specifies the name and path of the assembly file that contains the custom control.
- /r: Specifies the names of all the assemblies that are used by the code.
Control Class
The Control class includes functionalities to handle user input, define position and size of controls, and so on. The control class can be inherited by other classes to display information to the user. The properties of Control class.
- Bounds
Specifies or retrieves the size and location of the specified control with respect to its parent control.
- CanFocus
Retrieves a value that indicates whether the specified control can receive focus.
- CanSelect
Retrieves a value that indicates whether the specified control can be selected.
- Created
Retrieved a value that indicates whether the specified the specified control has been created.
Dock
Specifies or retrieves the control borders, which are docked to its parent control. It also identifies the way a control is resized with its parent.
Left
Retrieves the distance between the left edge of specified control and the left edge of the container’s client area.
- Right
Retrieves the distance between the right edge of specified control and the left edge of the container’s client area.
- TabIndex
Specifies or retrieves the tab order of the specified control within a container.
Table below the list of methods of control class.
Method |
Description |
Contains |
specifies control is a child of the control |
CreateControl |
Forcibly creates a control along with its handle and child controls. |
CreateGraphics |
Creates a graphic for the specified control. |
GetNextControl |
It retrieves the next control according to the specified tab order of child controls. |
GetPreferredSize |
It retrieves the size of the rectangular area. |
Hide |
Hides the specified control from the user. |
Below are the lists of events of Control class.
Event |
Description |
ControlAdded |
Occurs when a new control is added to a collection of controls. |
ControlRemoved |
Occurs when a specified control is removed from a collection of controls. |
Validated |
Occurs when the validation process of the specified control is complete. |
Code below creates a rectangular custom control and changes its appearance when the control is validated.
public partial class CustomControl: Control {
Graphics graphics;
protected override void OnPaint(PaintEventArgs pe) {
this.Bounds = new Rectangle(15, 15, 30, 15);
if (this.CanFocus) {
this.Focus();
}
this.Dock = DockStyle.None;
graphics = this.CreateGraphics();
graphics.FillRectangle / (Brushes.CornflowerBlue, ClientRectangle);
}
protected override void OnValidated(EventsArgs e) {
graphics.FillRectangle(Brushes.MediumOrchid, ClientRectangle);
graphics.DrawRectangle(new Pen(Color.Black, ClientRectangle);
}
}
In this code, the custom control is created by inheriting the Control class. When the OnPaint() method is invoked, the Bounds property is used to set a rectangular region. This is done by invoking the constructor of the Rectangular class, which takes the x and y coordinates, width and height as the parameters. The CanFocus property is used to check whether the control can receive focus. By default, it returns true and the focus() method is used to focus the control. The dock style for the control is set to None, which means that control cannot be dragged to some other location on the form. The graphics object Brush, is used to create the custom control within the specified rectangular bounds. When the validations are successfully made to the control, the OnValidated() method is invoked. This event changes the appearance of the control by changing its back color and border color.
The following code demonstrates how to override the Text and BackColor properties of the Control class. This is useful in setting the default values of the properties when the custom control appears on the form.
public partial class CustomLabel: Control {
private string labelText;
private Color bgColor = Color.darkBlue;
public override string Text {
get {
return labelText;
}
set {
labelText = value;
Invalidate();
}
}
public override Color BackColor {
get {
return bgColor;
}
set {
bgColor = value;
}
}
protected override void OnPaint(PaintEventArgs pe) {
Graphics graphics = this.CreateGraphics();
graphics.FillRectangle(new SolidBrush(bgColor), ClientRectangle);
graphics.DrawString(labelText, new Font(“Times”, 12), Brushes.Wheat, new Point(5, 5));
}
}
The Text property of the Control class is overridden. The BackColor property is also overridden to set the default color as dark blue. When the custom control is added to the form, the control appears with dark blue as the background color and customLabel as the default text. This text and background color appear on the label due to the Invalidate() method, which in turn, calls the OnPaint() method. This method redraws the control within the given client area along with the specified text and background color.
UserControl Class
The UserControl class allows the user to create controls that can be used in many places within an application of across multiple applications.
Table shows the properties of UserControl class
Property |
Description |
AutoSizeMode |
Specifies or retrieves the way a control will resize itself. |
AutoValidate |
Specifies or retrieved the way a control performs validation when the focus is switched to another control |
HorizontalScroll |
Retrieves the characteristics of the horizontal scroll bar. |
VerticalScroll |
Retrieves the characteristics of the vertical scroll bar. |
Table below the methods of UserControl class.
Method |
Description |
PerformAutoScale |
Performs automatic scaling of the specified container control and its child controls. |
ScrollControlView |
Scrolls the specified control into view. |
Table shows the events of UserControl class.
Event |
Description |
AutoValidateChanged |
It occurs when the value of AutoValidate property is changed. |
Load |
Before the specified control becomes visible for the first time. |
Code below shows how to create custom scroll bars using the UserControl class.
public partial class ScrollControl: UserControl {
protected override void OnPaint(PaintEventArgs e) {
this,
VerticalScroll,
Visible = true;
this.HorizontalScroll.Visible = true;
this.PerformAutoScale();
}
private void ScrollControl_Load(object sender, EventArgs e) {
this.VericalScroll.Minimum = 0;
this.VerticalScroll.Maximum = 100;
this.HorizontalScroll.Minimum = 0;
this.HorizontalScrollMaximum = 60;
}
}
The OnPaint() method is invoked to set the vertical and horizontal scroll bars. This is done using the VerticalScroll and HorizontalScroll properties of the UserControl class. The PerformAutoScale() method automatically scales the control and its container control. When the created custom control is loaded, the Load event is raised. When this event is raised, the Minimum and Maximum properties sets the minimum and maximum limits for both the scroll bars.
Control Type Recommendations
Windows Forms provide the user with a variety of options while working with controls. The user can either use the Windows Forms controls or create a new control. But, sometimes, the user might get confused about the type of control to be used in the application. The difference between various types of controls from which the user can inherit are listed as follows:
Inheriting Windows Forms Controls
Inheriting Windows Forms controls allows the user to implement the functionalities of the inherited control. The user can also extend the functionalities of the inherited control. The user can inherit from the Windows Forms control if the inheriting control fulfills most of the application’s requirements.
Inheriting the Control Class
The user can inherit from the Control class while customizing the appearance of the control. Also, inheriting the control class allows the user to implement the functionalities that are not provided by the standard controls.
Inheriting the UserControl Class
When the user wants to combine the functionalities of several Windows Forms controls, a user can create a composite control by inheriting the UserControl class.
Property- Changed Events
Windows Forms allows the user to send notifications when the value of the property is changed. The user can send notifications by defining an event and then a method that raises the event. The event name is the name of the property by appending the word, Changed, to the name of the property. For example, if the name of the property is BackColor, the user can define an event named BackColorChanged and the event-handler method named OnBackColorChanged.
Event handlers can be created to respond to property- change events. This allows developers to define various actions that can take place when a property of the control is changed.
Code below creates a custom TextBox control and raises an event when a value in the control is changed
public partial class TxtPrincipal: TextBox {
int years;
float rate;
double principal;
double interest;
protected override void OnTextChanged(EventArgs e) {
years = 10;
rate = 8.5 F;
principal = 0;
interest = 0;
try {
principal = Convert.ToDouble(this.Text);
interest = (principal * years * rate) / 100;
this.Parent.Text = ”Interest is: ”+interest.ToString();
} catch (Exception ex) {
MessageBox.Show(“Enter the numeric value only.”, ”ABCDBank”, MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Focus();
}
}
}
In this code, a custom textbox namely, TxtPrincipal is created. The OnTextChanged event is overridden and is raised when the value in the control is changed. The code calculated the interest using the values specified in the control.
Summary
User-defined controls can be created by inheriting the control class. UserControl class, or any windows forms existing control’s class. The HorizontalScroll and VerticalScroll properties of the UserControl class can be used to define custom scroll bars. The GetImage() method of the ToolBoxBitmapAttribute class retrieves the image icon associated with the custom control. Composite controls are user controls that are created using one or more Windows Forns controls. Property-changed events allows the user to send notification whenever the value of the property is changed.