Moisés Martínez Moisés Martínez - 2 months ago 30
C# Question

Change border color in TextBox C#

I have the following code:

public class OurTextBox : TextBox
{
public OurTextBox()
: base()
{
this.SetStyle(ControlStyles.UserPaint, true);
}

protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Pen penBorder = new Pen(Color.Gray, 1);
Rectangle rectBorder = new Rectangle(e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.Width - 1, e.ClipRectangle.Height - 1);
e.Graphics.DrawRectangle(penBorder, rectBorder);
}
}


This is working perfect, but it doesn't show the text until it gets focus.

Can anybody help me? What is wrong?

Thank in advance.

Answer

You have to draw text manually as well.

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    Pen penBorder = new Pen(Color.Gray, 1);
    Rectangle rectBorder = new Rectangle(e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.Width - 1, e.ClipRectangle.Height - 1);
    e.Graphics.DrawRectangle(penBorder, rectBorder);

    Rectangle textRec = new Rectangle(e.ClipRectangle.X + 1, e.ClipRectangle.Y + 1, e.ClipRectangle.Width - 1, e.ClipRectangle.Height - 1);
    TextRenderer.DrawText(e.Graphics, Text, this.Font, textRec, this.ForeColor, this.BackColor, TextFormatFlags.Default);
}

Alternatively you can try to use e.Graphics.DrawString() method if TextRenderer is not giving you desired results (I always have better results with this approach thou).