Change the borderColor of the TextBox

You can handle WM_NCPAINT message of TextBox and draw a border on the non-client area of control if the control has focus. You can use any color to draw border:

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class ExTextBox : TextBox
{
    [DllImport("user32")]
    private static extern IntPtr GetWindowDC(IntPtr hwnd);
    private const int WM_NCPAINT = 0x85;
    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if (m.Msg == WM_NCPAINT && this.Focused)
        {
            var dc = GetWindowDC(Handle);
            using (Graphics g = Graphics.FromHdc(dc))
            {
                g.DrawRectangle(Pens.Red, 0, 0, Width - 1, Height - 1);
            }
        }
    }
}

Result

The painting of borders while the control is focused is completely flicker-free:

BorderColor property for TextBox

In the current post I just change the border color on focus. You can also add a BorderColor property to the control. Then you can change border-color based on your requirement at design-time or run-time. I've posted a more completed version of TextBox which has BorderColor property: in the following post:

  • BorderColor property for TextBox


try this

bool focus = false;
private void Form1_Paint(object sender, PaintEventArgs e)
{
    if (focus)
    {
        textBox1.BorderStyle = BorderStyle.None;
        Pen p = new Pen(Color.Red);
        Graphics g = e.Graphics;
        int variance = 3;
        g.DrawRectangle(p, new Rectangle(textBox1.Location.X - variance, textBox1.Location.Y - variance, textBox1.Width + variance, textBox1.Height +variance ));
    }
    else
    {
        textBox1.BorderStyle = BorderStyle.FixedSingle;
    }
}

private void textBox1_Enter(object sender, EventArgs e)
{
    focus = true;
    this.Refresh();
}

private void textBox1_Leave(object sender, EventArgs e)
{
    focus = false;
    this.Refresh();
}

This is an ultimate solution to set the border color of a TextBox:

public class BorderedTextBox : UserControl
{
    TextBox textBox;

    public BorderedTextBox()
    {
        textBox = new TextBox()
        {
            BorderStyle = BorderStyle.FixedSingle,
            Location = new Point(-1, -1),
            Anchor = AnchorStyles.Top | AnchorStyles.Bottom |
                     AnchorStyles.Left | AnchorStyles.Right
        };
        Control container = new ContainerControl()
        {
            Dock = DockStyle.Fill,
            Padding = new Padding(-1)
        };
        container.Controls.Add(textBox);
        this.Controls.Add(container);

        DefaultBorderColor = SystemColors.ControlDark;
        FocusedBorderColor = Color.Red;
        BackColor = DefaultBorderColor;
        Padding = new Padding(1);
        Size = textBox.Size;
    }

    public Color DefaultBorderColor { get; set; }
    public Color FocusedBorderColor { get; set; }

    public override string Text
    {
        get { return textBox.Text; }
        set { textBox.Text = value; }
    }

    protected override void OnEnter(EventArgs e)
    {
        BackColor = FocusedBorderColor;
        base.OnEnter(e);
    }

    protected override void OnLeave(EventArgs e)
    {
        BackColor = DefaultBorderColor;
        base.OnLeave(e);
    }

    protected override void SetBoundsCore(int x, int y,
        int width, int height, BoundsSpecified specified)
    {
        base.SetBoundsCore(x, y, width, textBox.PreferredHeight, specified);
    }
}

WinForms was never good at this and it's a bit of a pain.

One way you can try is by embedding a TextBox in a Panel and then manage the drawing based on focus from there:

public class BorderTextBox : Panel {
  private Color _NormalBorderColor = Color.Gray;
  private Color _FocusBorderColor = Color.Blue;

  public TextBox EditBox;

  public BorderTextBox() {
    this.DoubleBuffered = true;
    this.Padding = new Padding(2);

    EditBox = new TextBox();
    EditBox.AutoSize = false;
    EditBox.BorderStyle = BorderStyle.None;
    EditBox.Dock = DockStyle.Fill;
    EditBox.Enter += new EventHandler(EditBox_Refresh);
    EditBox.Leave += new EventHandler(EditBox_Refresh);
    EditBox.Resize += new EventHandler(EditBox_Refresh);
    this.Controls.Add(EditBox);
  }

  private void EditBox_Refresh(object sender, EventArgs e) {
    this.Invalidate();
  }

  protected override void OnPaint(PaintEventArgs e) {
    e.Graphics.Clear(SystemColors.Window);
    using (Pen borderPen = new Pen(this.EditBox.Focused ? _FocusBorderColor : _NormalBorderColor)) {
      e.Graphics.DrawRectangle(borderPen, new Rectangle(0, 0, this.ClientSize.Width - 1, this.ClientSize.Height - 1));
    }
    base.OnPaint(e);
  }
}

Using OnPaint to draw a custom border on your controls is fine. But know how to use OnPaint to keep efficiency up, and render time to a minimum. Read this if you are experiencing a laggy GUI while using custom paint routines: What is the right way to use OnPaint in .Net applications?

Because the accepted answer of PraVn may seem simple, but is actually inefficient. Using a custom control, like the ones posted in the answers above is way better.

Maybe the performance is not an issue in your application, because it is small, but for larger applications with a lot of custom OnPaint routines it is a wrong approach to use the way PraVn showed.


Comments

  1. Matteo

    • 2021/5/3

    In the current post I just change the border color on focus. You can also add a BorderColor property to the control. Then you can change border- 

  2. Thompson

    • 2015/9/6

    public class BorderTextBox : Panel { private Color _NormalBorderColor = Color.Gray; private Color _FocusBorderColor = Color.Blue; public TextBox EditBox; public BorderTextBox() { this.DoubleBuffered = true; this.Padding = new Padding(2); EditBox = new TextBox(); EditBox.AutoSize = false; EditBox.BorderStyle = BorderStyle.None; EditBox.Dock = DockStyle.Fill; EditBox.Enter += new EventHandler(EditBox_Refresh); EditBox.Leave += new EventHandler(EditBox_Refresh); EditBox.Resize += new

  3. Alex

    • 2021/2/6

    A TextBox does not have a Paint event handler. Because of that, you cannot modify things like the Border Color.

  4. Trenton

    • 2018/7/12

    The BorderColor property setting is a numeric expression that corresponds to the color that you want to use for a control's border. You can set the default for this property by using a control's default control style or the DefaultControl property in Visual Basic. A control's border color is visible only when its SpecialEffect property is set to Flat or Shadowed.

  5. Ernesto

    • 2015/7/17

    You have some options: 1) A quick and dirty approach: put a Label behind the TextBox and make the label a little bigger than the 

  6. Mac

    • 2016/5/15

    How to change Textbox BorderColor in C#? Solution 3. In order to work with the events of the inner TextBox, directly from your UserControl, you can expose the Solution 2. Use the BackColor property of the Label to give the TextBox a different border color. See this [ ^] thread Solution 1. I

  7. Stephen

    • 2016/9/9

    To change border color of TextBox you can override WndProc method and handle WM_NCPAINT message. Then get the window device context of the control using 

  8. Green

    • 2019/8/23

    textBox.BorderStyle = BorderStyle.None; this.Controls.Add(textBox); } private void UserControl1_Resize(object sender, EventArgs e) { textBox.Size = new Size (this.Width - 3, this.Height - 2); textBox.Location = new Point (2, 1); }

  9. Jabari

    • 2019/3/2

    All replies · Handle the Paint event of the form (or the panel/control that the textbox resides on) · Make a rectangle that is inflated around the 

  10. Benson

    • 2018/6/2

    On the Drawing Tools Format tab, click Shape Outline and, under Theme Colors, pick the color you want. To change the border to a color that isn't in the theme colors. Select the shape or text box. On the Drawing Tools Format tab, click Shape Outline, and then click More Outline Colors.

  11. Karson

    • 2020/9/22

    You can change the color and styles of the border of the TextBoxExt control by using Border3DStyle, BorderColor, BorderSides and BorderStyle properties.

  12. Landry

    • 2017/11/14

    VB. Private Sub ToggleButton2_Click () 'Set background to Opaque or Transparent If ToggleButton2.Value = True Then 'Change TextBox2 to a transparent background TextBox2.BackStyle = fmBackStyleTransparent Else 'Change TextBox2 back to opaque background TextBox2.BackStyle = fmBackStyleOpaque End If End Sub.

  13. Tristen

    • 2017/8/23

    how to change border color of a textbox in c# windows application? Hello,. technically, there is no "border color" for a textbox. what you can 

  14. Morel

    • 2017/10/20

    The code will toggle a red border around a text box by pressing a button. Its hard coded for a 3d border size Private Sub GroupBox1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles GroupBox1.Paint 'If the textbox's region hasn't been set then this will draw behind 'the textbox.

  15. Luis

    • 2020/4/4

    How to change Textbox Border Width, Border Style and Border Color programmatically in ASP.NET. Change Textbox Border Style on Button click event .net c#.

  16. Mark

    • 2015/11/17

    I am trying to find a simple way to change the border color of a text box when the cursor is in the box. I would like the text box to have a black border wh 

  17. Elliott

    • 2015/6/9

    asp.net web server control BorderColor property accept standard color name as it value. we can assign any valid color name for textbox border color. colored 

Comments are closed.

Recent Posts