在 VS2010+ 中將 TextBox 渲染為圓角矩形或橢圓形邊框,而非默認矩形。
| 方案 | 優點 | 缺點 | 適用版本 |
|---|---|---|---|
| 重寫 OnPaint / WndProc | 無第三方依賴,完全可控 | 需處理邊框、焦點、滾動條繪制,代碼量大 | .NET 2.0+ |
| 使用 Panel + TextBox 組合 | 簡單:Panel 畫圓角背景,TextBox 設 BorderStyle=None、BackColor=Transparent | 需精確對齊內邊距,高 DPI 可能偏移 | 所有版本 |
| 第三方控件庫 | 功能豐富(水印、圖標、驗證) | 引入依賴,可能收費 | 視庫而定 |
| WPF / MAUI | 原生支持幾何圖形裁剪 | 技術棧不同,遷移成本高 | .NET 3.0+ / .NET 6+ |
// 設計器中操作:
// 1. 拖入 Panel,設置:
panel1.BackColor = Color.White; // 內部背景
panel1.Padding = new Padding(5); // 內邊距,防止文字貼邊
panel1.Size = new Size(200, 30); // 整體尺寸
// 2. 拖入 TextBox 到 Panel 內,設置:
textBox1.BorderStyle = BorderStyle.None; // 去掉自帶邊框
textBox1.BackColor = Color.Transparent; // 透明背景,顯示 Panel 背景
textBox1.Dock = DockStyle.Fill; // 填滿 Panel 內部
textBox1.Font = new Font("微軟雅黑", 10);
// 3. Panel 繪制圓角邊框 (在 Panel 的 Paint 事件)
private void panel1_Paint(object sender, PaintEventArgs e) {
var rect = panel1.ClientRectangle;
rect.Inflate(-1, -1); // 留 1px 畫筆寬度
using (var path = new GraphicsPath()) {
int radius = 10; // 圓角半徑
path.AddArc(rect.X, rect.Y, radius*2, radius*2, 180, 90);
path.AddArc(rect.Right - radius*2, rect.Y, radius*2, radius*2, 270, 90);
path.AddArc(rect.Right - radius*2, rect.Bottom - radius*2, radius*2, radius*2, 0, 90);
path.AddArc(rect.X, rect.Bottom - radius*2, radius*2, radius*2, 90, 90);
path.CloseFigure();
panel1.Region = new Region(path); // 關鍵:裁剪控件區域,實現真正圓角點擊
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
using (var pen = new Pen(Color.Gray, 1))
e.Graphics.DrawPath(pen, path);
}
}
public class RoundedTextBox : Panel {
private TextBox _txt = new TextBox();
public RoundedTextBox() {
_txt.BorderStyle = BorderStyle.None;
_txt.BackColor = Color.Transparent;
_txt.Dock = DockStyle.Fill;
_txt.Font = new Font("微軟雅黑", 10);
this.Controls.Add(_txt);
this.Padding = new Padding(5);
this.BackColor = Color.White;
this.Size = new Size(200, 30);
this.Resize += (s, e) => this.Invalidate();
}
public string Text { get => _txt.Text; set => _txt.Text = value; }
// 暴露常用屬性/事件...
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
// 同上圓角繪制代碼
}
}
panel.Region 可使點擊圓角外區域不聚焦,體驗更真實。OnPaint 中使用 e.Graphics.DpiX 縮放半徑,或啟用 Per-Monitor DPI Awareness。OnPaint 繪制灰色提示文字,或用 SendMessage(EM_SETCUEBANNER)。