Change border color in TextBox C#

前端 未结 4 1975
面向向阳花
面向向阳花 2020-11-28 10:42

I have the following code:

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


        
4条回答
  •  孤城傲影
    2020-11-28 11:31

    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 a Panel as follows.

    public class BorderedTextBox : Panel 
    {
        private TextBox textBox;
        private bool focusedAlways = false;
        private Color normalBorderColor = Color.Gray;
        private Color focusedBorderColor = Color.Red;
    
        public BorderTextBox() 
        {
            this.DoubleBuffered = true;
            this.Padding = new Padding(2);
    
            this.TextBox = new TextBox();
            this.TextBox.AutoSize = false;
            this.TextBox.BorderStyle = BorderStyle.None;
            this.TextBox.Dock = DockStyle.Fill;
            this.TextBox.Enter += new EventHandler(this.TextBox_Refresh);
            this.TextBox.Leave += new EventHandler(this.TextBox_Refresh);
            this.TextBox.Resize += new EventHandler(this.TextBox_Refresh);
            this.Controls.Add(this.TextBox);
        }
    
        private void TextBox_Refresh(object sender, EventArgs e) 
        {
            this.Invalidate();
        }
    
        protected override void OnPaint(PaintEventArgs e) 
        {
            e.Graphics.Clear(SystemColors.Window);
            using (Pen borderPen = new Pen(this.TextBox.Focused || FocusedAlways ? 
                focusedBorderColor : normalBorderColor)) 
            {
                e.Graphics.DrawRectangle(borderPen, 
                    new Rectangle(0, 0, this.ClientSize.Width - 1, this.ClientSize.Height - 1));
            }
            base.OnPaint(e);
        }
    
        public TextBox TextBox
        {
            get { return textbox; }
            set { textbox = value; }
        }
    
        public bool FocusedAlaways
        {
            get { return focusedAlways; }
            set { focusedAlways = value; }
        }
    }
    

    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 to True.

    I hope this helps.

提交回复
热议问题