C# 更改文本框的边框颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9768938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:46:53  来源:igfitidea点击:

Change the borderColor of the TextBox

c#.netwinformstextboxborder

提问by Raggy Shrestha

How can I change the BorderColor of the Textbox when a user Clicks on it or focuses on it?

当用户单击或关注文本框时,如何更改文本框的边框颜色?

采纳答案by PraveenVenu

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();
        }

回答by Balazs Tihanyi

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

这是设置 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);
    }
}

回答by LarsTech

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

WinForms 从来不擅长这个,这有点痛苦。

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);
  }
}

回答by Mike de Klerk

Using OnPaintto draw a custom border on your controls is fine. But know how to use OnPaintto 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?

OnPaint画上你控制一个自定义边框的罚款。但知道如何使用OnPaint以保持效率,并将渲染时间降至最低。如果您在使用自定义绘制例程时遇到延迟的 GUI,请阅读本文:在 .Net 应用程序中使用 OnPaint 的正确方法是什么?

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.

因为 PraVn 的公认答案可能看起来很简单,但实际上效率很低。使用自定义控件(如上面答案中发布的控件)会更好。

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.

也许性能在您的应用程序中不是问题,因为它很小,但是对于具有大量自定义 OnPaint 例程的大型应用程序,使用 PraVn 显示的方式是错误的方法。

回答by Moory Pc

set Text box Border style to None then write this code to container form "paint" event

将文本框边框样式设置为无,然后将此代码写入容器表单“绘制”事件

private void Form1_Paint(object sender, PaintEventArgs e)
        {
System.Drawing.Rectangle rect = new Rectangle(TextBox1.Location.X, TextBox1.Location.Y, TextBox1.ClientSize.Width, TextBox1.ClientSize.Height);

                rect.Inflate(1, 1); // border thickness
                System.Windows.Forms.ControlPaint.DrawBorder(e.Graphics, rect, Color.DeepSkyBlue, ButtonBorderStyle.Solid);

}

回答by Reza Aghaei

You can handle WM_NCPAINTmessage of TextBoxand draw a border on the non-client area of control if the control has focus. You can use any color to draw border:

如果控件具有焦点,您可以处理控件的非客户区域的WM_NCPAINT消息TextBox并在其上绘制边框。您可以使用任何颜色来绘制边框:

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:

控件聚焦时的边框绘制完全无闪烁:

Change TextBox border color on focus

更改焦点上的文本框边框颜色

BorderColor property for TextBox

TextBox 的 BorderColor 属性

In the current post I just change the border color on focus. You can also add a BorderColorproperty 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 TextBoxwhich has BorderColorproperty: in the following post:

在当前的帖子中,我只是更改了焦点的边框颜色。您还可以BorderColor向控件添加属性。然后您可以在设计时或运行时根据您的要求更改边框颜色。我已经发布了一个更完整的版本,TextBox其中有BorderColor属性:在以下帖子中:

Change Textbox border color

更改文本框边框颜色

回答by Sunil

Isn't it Simple as this,

是不是就这么简单,

txtbox1.BorderColor = System.Drawing.Color.Red;

txtbox1.BorderColor = System.Drawing.Color.Red;