首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

WinForms TextBox 控件實現圓角/橢圓邊框

     編輯:程式設計綜合問答

需求

在 VS2010+ 中將 TextBox 渲染為圓角矩形或橢圓形邊框,而非默認矩形。

方案對比

方案優點缺點適用版本
重寫 OnPaint / WndProc無第三方依賴,完全可控需處理邊框、焦點、滾動條繪制,代碼量大.NET 2.0+
使用 Panel + TextBox 組合簡單:Panel 畫圓角背景,TextBox 設 BorderStyle=None、BackColor=Transparent需精確對齊內邊距,高 DPI 可能偏移所有版本
第三方控件庫功能豐富(水印、圖標、驗證)引入依賴,可能收費視庫而定
WPF / MAUI原生支持幾何圖形裁剪技術棧不同,遷移成本高.NET 3.0+ / .NET 6+

推薦:Panel + TextBox 組合(最省事)

// 設計器中操作:
// 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);
        // 同上圓角繪制代碼
    }
}

注意事項

  • Region 裁剪:設置 panel.Region 可使點擊圓角外區域不聚焦,體驗更真實。
  • 高 DPI:在 OnPaint 中使用 e.Graphics.DpiX 縮放半徑,或啟用 Per-Monitor DPI Awareness。
  • Placeholder/水印:需自行在 OnPaint 繪制灰色提示文字,或用 SendMessage(EM_SETCUEBANNER)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved