You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 7.3中自定义圆角矩形按钮失败,求解决方案

在C# 7.3中实现圆角矩形按钮的正确方式

当然可以在C# 7.3中实现圆角按钮,你当前的代码存在两个核心问题:一是没有将创建的圆角区域绑定到按钮上,二是用多边形构建的路径并不是真正的圆角矩形,只是近似的六边形。以下是修正后的完整实现:

自定义圆角按钮类

public class RoundCorneredButton : Button
{
    // 暴露圆角半径属性,方便外部调整
    public int CornerRadius { get; set; } = 10;

    public RoundCorneredButton()
    {
        // 开启双缓冲避免绘制闪烁
        DoubleBuffered = true;
        // 使用Flat样式,避免系统默认立体边框覆盖自定义绘制
        FlatStyle = FlatStyle.Flat;
        FlatAppearance.BorderSize = 1;
        FlatAppearance.MouseOverBackColor = Color.LightBlue;
        FlatAppearance.MouseDownBackColor = Color.DarkBlue;
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        // 使用using自动释放GraphicsPath资源
        using (GraphicsPath path = new GraphicsPath())
        {
            int radius = CornerRadius;
            // 依次绘制四个角落的圆弧,构建完整圆角路径
            path.AddArc(0, 0, radius, radius, 180, 90);
            path.AddArc(Width - radius, 0, radius, radius, 270, 90);
            path.AddArc(Width - radius, Height - radius, radius, radius, 0, 90);
            path.AddArc(0, Height - radius, radius, radius, 90, 90);
            path.CloseAllFigures();

            // 将路径设置为按钮的显示区域,裁剪超出圆角的部分
            this.Region = new Region(path);

            // 调用基类绘制逻辑,确保文本、焦点框等元素正常显示
            base.OnPaint(e);
        }
    }

    // 按钮尺寸变化时触发重绘,保证圆角始终适配当前大小
    protected override void OnSizeChanged(EventArgs e)
    {
        base.OnSizeChanged(e);
        Invalidate();
    }
}

窗体中使用自定义按钮

public partial class Form1 : Form
{
    private RoundCorneredButton _customButton;

    public Form1()
    {
        InitializeComponent();
        DoubleBuffered = true;

        _customButton = new RoundCorneredButton();
        _customButton.Text = "Custom Button";
        _customButton.Size = new Size(200, 100);
        _customButton.Location = new Point(50, 50);
        // 可根据需求调整圆角半径
        _customButton.CornerRadius = 15;
        Controls.Add(_customButton);
    }
}

关键实现说明

  • 绑定显示区域:必须将GraphicsPath转换为Region并赋值给按钮的Region属性,系统才会按照圆角路径裁剪按钮的显示范围。
  • 标准圆角路径:使用AddArc绘制四个角落的圆弧,再通过CloseAllFigures闭合路径,这是构建圆角矩形的标准方式,比多边形近似更精准。
  • 样式与性能优化:开启双缓冲避免绘制闪烁,设置FlatStyle.Flat可以规避系统默认的立体边框,同时通过FlatAppearance自定义按钮的 hover、按下等交互状态样式。
  • 适配尺寸变化:重写OnSizeChanged方法,在按钮大小改变时触发重绘,确保圆角始终匹配当前按钮尺寸。

内容的提问来源于stack exchange,提问作者user2102327

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 23:45:18