Windows Forms中如何移除TextBox的顶部及两侧边框
Windows Forms中如何移除TextBox的顶部及两侧边框
嘿,我明白你想要的效果——让TextBox只保留底部边框,去掉顶部和两侧的边框对吧?Windows Forms自带的TextBox确实没有直接提供设置部分边框的属性,但有两个简单的方法可以实现这个需求:
方法一:用Label模拟底部边框(快速实现)
这种方法不需要自定义控件,直接用现有控件组合就能搞定:
- 先把你的TextBox边框设为无:
this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None; - 添加一个Label作为底部边框,把它放在TextBox的正下方:
Label bottomBorder = new Label(); // 对齐TextBox的底部 bottomBorder.Location = new Point(textBox1.Left, textBox1.Top + textBox1.Height); // 宽度和TextBox一致,高度设为1(边框厚度) bottomBorder.Size = new Size(textBox1.Width, 1); // 设置边框颜色,这里用系统默认的控件深色,你也可以换成Color.Black之类的自定义颜色 bottomBorder.BackColor = SystemColors.ControlDark; // 添加到窗体控件集合 this.Controls.Add(bottomBorder); // 确保Label在TextBox后面,不会挡住输入 bottomBorder.BringToFront(); textBox1.BringToFront();
方法二:自定义TextBox控件(适合复用)
如果你需要在多个地方使用这种样式的TextBox,自定义控件会更方便:
创建一个继承自TextBox的自定义类,重写OnPaint方法只绘制底部边框:
public class CustomTextBox : TextBox { public CustomTextBox() { // 先关闭默认边框,开启自定义绘制 this.BorderStyle = BorderStyle.None; this.SetStyle(ControlStyles.UserPaint, true); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); // 绘制底部边框,这里可以调整颜色和厚度 using (Pen borderPen = new Pen(SystemColors.ControlDark, 1)) { // 从控件左下角画到右下角 e.Graphics.DrawLine(borderPen, 0, this.Height - 1, this.Width, this.Height - 1); } } }
之后你就可以在窗体里直接使用这个CustomTextBox,它会自动只显示底部边框,不用每次都重复设置啦。
备注:内容来源于stack exchange,提问作者Mark Philips
相关产品推荐
相关产品推荐

