Custom Text Box - Custom Controls WinForm C # - RJ Code Advance

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

7/22/2021 Custom Text Box - Custom controls WinForm C # - RJ Code Advance

Hack Não 1500 Từ Vựng T.A


Nạp Siêu Tốc 1500 Từ Trong 50 Ngày - Phát Huy 80% Năng Lực Não

stepup.edu.vn

Custom Text Box - Custom controls


WinForm C #
by RJ Code Advance

https://rjcodeadvance.com/custom-text-box-custom-controls-winform-c/ 1/14
7/22/2021 Custom Text Box - Custom controls WinForm C # - RJ Code Advance

Hi :), this time we will create a custom textbox with C # and Windows Form. And thus have a
text box with a very elegant, flat and modern appearance, with customizable size and border
color, to be able to set an underlined or rectangular border style. Besides being able to set
and change the border color in focus mode, set as password field and multiline.

Doing it is very easy and fast, you don't need to have advanced programming knowledge, so
let's start with the tutorial:

1.- Add User Control


First we must add a user control to create the custom text box through the designer and
code . Or you can add a class and inherit from the user control class and create the
custom text box using code only.

2.- Design the basic appearance - Designer


After adding the UserControl , initialize the following properties: In the AutoScaleMode
property set to none, and a Padding of 7 pixels on all sides, this is very important as it will
help the text box to be centered in the control of Username. Resize the user control to a
width of 250 and a height of 30 . Optionally set the background color, text color and we
will increase the text size.

2.1.- Add TextBox

https://rjcodeadvance.com/custom-text-box-custom-controls-winform-c/ 2/14
7/22/2021 Custom Text Box - Custom controls WinForm C # - RJ Code Advance

After having initialized the previous properties, it only remains to add a text box to the user
control and set the Dock property of the text box to FILL , to fit the entire user control.
And finally remove the border from the text box . In this way, the text box remains
centered on the user control, thanks to the Padding established above.

-Transcription of the code - RJTextBox.Designer.cs


#region Component Designer generated code
private void InitializeComponent ()
{
this . textBox1 = new System. Windows . Forms . TextBox () ;
this . SuspendLayout () ;
//
// textBox1
//
this . textBox1 . BorderStyle = System. Windows . Forms . BorderStyle . N
this . textBox1 . Dock = System. Windows . Forms . DockStyle . Fill ;
this . textBox1 . Location = new System. Drawing . Point ( 7 , 7 ) ;
this . textBox1 . Name = "textBox1" ;
this . textBox1 . Size = new System. Drawing . Size ( 236 , 15 ) ;
//
// RJTextBox
//
this . AutoScaleMode = System. Windows . Forms . AutoScaleMode . None ;
this . BackColor = System. Drawing . SystemColors . Window ;
this . Controls . Add ( this . TextBox1 ) ;
this . Font = new System. Drawing . Font ( "Microsoft Sans Serif" , 9.5 F
this . ForeColor = System. Drawing . Color . DimGray ;
this . Margin = new System. Windows . Forms . Padding ( 4 ) ;
this . Name = "RJTextBox" ;
this . Padding = new System. Windows . Forms . Padding ( 7 ) ;
this . Size = new System. Drawing . Size ( 250 , 30 ) ;
this . ResumeLayout ( false ) ;
this . PerformLayout () ;
}
https://rjcodeadvance.com/custom-text-box-custom-controls-winform-c/ 3/14
7/22/2021 Custom Text Box - Custom controls WinForm C # - RJ Code Advance

#endregion

private System. Windows . Forms . TextBox textBox1;

3.- Declare fields - Code


Once the basic design of the custom text box is done, now it only remains to open the User
Control Code and do the rest, and as usual, we will declare some fields for the appearance
and initialize their default values. In this case, a field for the border color, a field for the
border size, and a field for the style of the text box, that is, an underlined or rectangular
border style.

// Fields
private Color borderColor = Color. MediumSlateBlue ;
private int borderSize = 2 ;
private bool underlinedStyle = false ;
private Color borderFocusColor = Color. HotPink ;
private bool isFocused = false ;

4.- Create a method to establish the appropriate height of the control


The method will take care of setting a suitable height for the user control (RJTextBox)
and text box (textBox1), and also restrict the height change when the text box is not
multiline (textBox1.Multiline = false).

// Private methods
private void UpdateControlHeight ()
{
if ( textBox1. Multiline == false )
{
int txtHeight = TextRenderer. MeasureText ( "Text" , this . Font ) .
textBox1. Multiline = true ;
textBox1. MinimumSize = new Size ( 0 , txtHeight ) ;
textBox1. Multiline = false ;

this . Height = textBox1. Height + this . Padding . Top + this . Padd


}
}

5.- Create the access descriptors - Properties


We generate properties to expose the fields defined previously, and in addition to adding
other appearance properties (Background color, text…) and exposing the functional and
necessary properties for a text box (PasswordChar, Multiline, Text…).

https://rjcodeadvance.com/custom-text-box-custom-controls-winform-c/ 4/14
7/22/2021 Custom Text Box - Custom controls WinForm C # - RJ Code Advance

// Properties
[ Category ( "RJ Code Advance" )]
public Color BorderColor
{
get { return borderColor; }
set
{
borderColor = value ;
this . Invalidate () ;
}
}
[ Category ( "RJ Code Advance" )]
public int BorderSize
{
get { return borderSize; }
set
{
borderSize = value ;
this . Invalidate () ;
}
}

[ Category ( "RJ Code Advance" )]


public bool UnderlinedStyle
{
get { return underlinedStyle; }
set
{
underlinedStyle = value ;
this . Invalidate () ;
}
}

[ Category ( "RJ Code Advance" )]


public bool PasswordChar
{
get { return textBox1. UseSystemPasswordChar ; }
set { textBox1. UseSystemPasswordChar = value ; }
}

[ Category ( "RJ Code Advance" )]


public bool Multiline
{
get { return textBox1. Multiline ; }
set { textBox1. Multiline = value ; }
}

[ Category ( "RJ Code Advance" )]


public override Color BackColor
https://rjcodeadvance.com/custom-text-box-custom-controls-winform-c/ 5/14
7/22/2021 Custom Text Box - Custom controls WinForm C # - RJ Code Advance

{
get { return base . BackColor ; }
set
{
base . BackColor = value ;
textBox1. BackColor = value ;
}
}

[ Category ( "RJ Code Advance" )]


public override Color ForeColor
{
get { return base . ForeColor ; }
set
{
base . ForeColor = value ;
textBox1. ForeColor = value ;
}
}

[ Category ( "RJ Code Advance" )]


public override Font Font
{
get { return base . Font ; }
set
{
base . Font = value ;
textBox1. Font = value ;
if ( this . DesignMode )
UpdateControlHeight () ;
}
}

[ Category ( "RJ Code Advance" )]


public string Texts
{
get { return textBox1. Text ; }
set { textBox1. Text = value ; }
}

[ Category ( "RJ Code Advance" )]


public Color BorderFocusColor
{
get { return borderFocusColor; }
set { borderFocusColor = value ; }
}

6.- Override and extend event methods - UserControl


https://rjcodeadvance.com/custom-text-box-custom-controls-winform-c/ 6/14
7/22/2021 Custom Text Box - Custom controls WinForm C # - RJ Code Advance

It will be necessary to override the OnPaint event method to draw the rectangular or
underlined border of the custom text box, override the OnResize event method to set the
proper height of the control each time it resizes at design time. Finally override the OnLoad
event method to give the final touch and set the proper height at runtime.

// Overridden methods

protected override void OnPaint ( PaintEventArgs e )


{
base . OnPaint ( e ) ;
Graphics graph = e. Graphics ;

// Draw border
using ( Pen penBorder = new Pen ( borderColor, borderSize ))
{
penBorder. Alignment = System. Drawing . Drawing2D . PenAlignment . I
if ( isFocused ) penBorder. Color = borderFocusColor ; // Set Border

if ( underlinedStyle ) // Line Style


graph. DrawLine ( penBorder, 0 , this . Height - 1 , this . Width
else // Normal Style
graph. DrawRectangle ( penBorder, 0 , 0 , this . Width - 0.5 F, t
}
}

protected override void OnResize ( EventArgs e )


{
base . OnResize ( e ) ;
if ( this . DesignMode )
UpdateControlHeight () ;
}

protected override void OnLoad ( EventArgs e )


{
base . OnLoad ( e ) ;
UpdateControlHeight () ;
}

7.- Change border color in focus mode


For that purpose it is necessary to change the value of the isFocused field when the text box
enters the focused state or loses focus. So we need to subscribe the Enter-Focus and Leave-
Focus event of the text box and redraw the control.

// Change border color in focus mode


private void textBox1_Enter ( object sender, EventArgs e )

https://rjcodeadvance.com/custom-text-box-custom-controls-winform-c/ 7/14
7/22/2021 Custom Text Box - Custom controls WinForm C # - RJ Code Advance

{
isFocused = true ;
this . Invalidate () ;
}

private void textBox1_Leave ( object sender, EventArgs e )


{
isFocused = false ;
this . Invalidate () ;
}

8.- Create default event of the custom text box


The default event for a user control is the Load event , and the default event for a text box
is the TextChanged event . Therefore we must recreate this event in the custom text box
(RJTextBox), since the current default event is the Load event.

Note: To know what the default event of a control is, you just have to double click on the
control and the default event method will be created.

[ DefaultEvent ( "_TextChanged" )]
public partial class RJTextBox: UserControl
{

// Default Event
public event EventHandler _TextChanged;

// TextBox-> TextChanged event


private void textBox1_TextChanged ( object sender, EventArgs e )
{
if ( _TextChanged! = null )
_TextChanged. Invoke ( sender, e ) ;
}

9.- Attach other common existing events


Finally, it is necessary to attach the existing and common events between the user control
(RJTextBox) and the text box (textBox1), for example the Click event, KeyPress and among
others (It is only recommended to attach the necessary events).

// TextBox events
/// <summary>
/// textbox events attached to user control events
/// </summary>

private void textBox1_Click ( object sender, EventArgs e )


{

https://rjcodeadvance.com/custom-text-box-custom-controls-winform-c/ 8/14
7/22/2021 Custom Text Box - Custom controls WinForm C # - RJ Code Advance

this . OnClick ( e ) ;
}

private void textBox1_MouseEnter ( object sender, EventArgs e )


{
this . OnMouseEnter ( e ) ;
}

private void textBox1_MouseLeave ( object sender, EventArgs e )


{
this . OnMouseLeave ( e ) ;
}

private void textBox1_KeyPress ( object sender, KeyPressEventArgs e )


{
this . OnKeyPress ( e ) ;
}

Well that's it :), I hope you liked it and helped you understand the use of user controls
alongside other controls to make custom controls.

Until next time.

SEE FULL CODE (GITHUB)

See video tutorial

Custom TextBox - Border, Focus Color, Underlined Style - WinForm C#

https://rjcodeadvance.com/custom-text-box-custom-controls-winform-c/ 9/14
7/22/2021 Custom Text Box - Custom controls WinForm C # - RJ Code Advance

Leave a reply
Your email address will not be published. Required fields are marked with *

Commentary

Name *

E-mail *

Web

Post the comment

Welcome to blog

Look for …

https://rjcodeadvance.com/custom-text-box-custom-controls-winform-c/ 10/14
7/22/2021 Custom Text Box - Custom controls WinForm C # - RJ Code Advance

Follow me




Category:
.NET
ASP .NET
C#
Mistakes
F#
Visual basic
Windows Forms

Layered Architecture

https://rjcodeadvance.com/custom-text-box-custom-controls-winform-c/ 11/14
7/22/2021 Custom Text Box - Custom controls WinForm C # - RJ Code Advance

Database
MySQL
SQL Server
Custom controls
courses
.NET (Course)
Create .Net Installer
Full Login C #, VB, SQL Server
Software Patterns (Course)
OOP (Course)
Desk
GUI
Software Patterns
OOP
Uncategorized
Web

Recent logins
Circular Picture Box - Border Gradient color + Styles - C # & WinForms
Custom ProgressBar - WinForms & C #
Custom TextBox Full - Rounded & Placeholder - WinForm, C #
Custom ComboBox - Icon, Back, Text & Border Color - WinForm C #
Custom Text Box - Custom controls WinForm C #

Recent comments
gustavo on Custom Button - Custom controls WinForm C #
_Nooker in Modern Form + Font Awesome Icons, WinForm, C # - VB.NET

https://rjcodeadvance.com/custom-text-box-custom-controls-winform-c/ 12/14
7/22/2021 Custom Text Box - Custom controls WinForm C # - RJ Code Advance

Impekly in Full Login + CRUD - C #, SQL Server- Advanced Level


Willgt27 in Login Cap 2- Start Session, Close Session and Show user data with C #, VB.Net,
Sql Server, WinForm- POO, Layered Architecture- Intermediate Level
Juan Vega in Chapter 4 / Create Installation Package - Application with Local Network
Database (LAN-MAN) - SQL Server, Visual Studio, WinForm, Layers

Terms and Conditions Privacy Policy Cookies policy




© 2021 RJ Code Advance - All Rights Reserved

https://rjcodeadvance.com/custom-text-box-custom-controls-winform-c/ 13/14
7/22/2021 Custom Text Box - Custom controls WinForm C # - RJ Code Advance

https://rjcodeadvance.com/custom-text-box-custom-controls-winform-c/ 14/14

You might also like