更改TextBox

时间:2016-02-24 04:10:35

标签: winforms textbox styles border custom-controls

有没有办法可以自定义winform文本框控件的边框样式,如下图所示?

enter image description here

我确实在互联网上搜索了我的问题的答案,但没有相关的结果隐藏顶部,左边,右边框,底部边框是点缀式。

我想知道我能用winform控制吗?

请指教!

1 个答案:

答案 0 :(得分:0)

您可以做的一件事是继承Panel类并将TextBox封装在其中。然后覆盖该Panel的OnPaint事件以绘制所需的内容。

public class CustomTextBox : Panel
{
    private Color _nBorderColor = Color.Gray;
    private Color _fBorderColor = Color.Black;

    public TextBox _textBox;

    public CustomTextBox()
    {
        this.DoubleBuffered = true;
        this.Padding = new Padding(2);

        _textBox = new TextBox();
        _textBox.AutoSize = false;
        _textBox.BorderStyle = BorderStyle.None;
        _textBox.Dock = DockStyle.Fill;
        _textBox.Enter += new EventHandler(TextBox_Refresh);
        _textBox.Leave += new EventHandler(TextBox_Refresh);
        _textBox.Resize += new EventHandler(TextBox_Refresh);
        this.Controls.Add(_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 ? _fBorderColor : _nBorderColor))
        {
            borderPen.DashStyle = DashStyle.Dot;
            borderPen.Width = 3;
            e.Graphics.DrawLine(borderPen, 0, this.ClientSize.Height - 1, this.ClientSize.Width - 1, this.ClientSize.Height - 1);
        }
        base.OnPaint(e);
    }
}