How can I change the BorderColor of the Textbox when a user Clicks on it or focuses on it?
Solution 4 You can use Enter event for this. And also if you want to change the color of first text box to the default color when you go to the next text box, that can be done with leave event. Use this code. Bind those events to the two text boxes.
Simply select the object you want to modify while in Layout or Design view and use the formatting options on the Format tab to customize its appearance. Access colour palette can be manipulated to give you other colours. In the palette source, select Define Custom Colors.
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:
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With