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.
You have to draw text manually as well.
Alternatively you can try to use
e.Graphics.DrawString()
method ifTextRenderer
is not giving you desired results (I always have better results with this approach thou).To change border color of
TextBox
you can overrideWndProc
method and handleWM_NCPAINT
message. Then get the window device context of the control usingGetWindowDC
because we want to draw to non-client area of control. Then to draw, it's enough to create aGraphics
object from that context, then draw border for control.To redraw the control when the
BorderColor
property changes, you can useRedrawWindow
method.Code
Here is a
TextBox
which has aBorderColor
property. The control usesBorderColor
if the property values is different thanColor.Transparent
andBorderStyle
is its default valueFixed3d
.Result
Here is the result using different colors and different states. All states of border-style is supported as you can see in below image and you can use any color for border:
Download
You can clone or download the working example:
set Text box Border style to None then write this code to container form "paint" event
There are several ways to do this and none are ideal. This is just the nature of WinForms. However, you have some options. I will summarise:
One way you can achieve what you want is by embedding a
TextBox
in aPanel
as follows.You can also do this without overriding any controls, but the above method is better. The above will draw a border when the control gets focus. if you want the border on permanently, set the
FocusedAlways
property toTrue
.I hope this helps.