C#自定义checkBox开关按钮控件,设计漂亮美观的UI按钮
第一步:
先准备开关按钮要使用到的背景图片,一张是开启的,一张是关闭的,如下图:
一共有6种款式,大家也可以全部加进去
然后将这些图片作为资源文件添加到项目中,如下图:
第二步、新建用户控件,命名为:ButtonCheck.cs
ButtonCheck.cs 代码如下:

/// <summary> /// 是否选中 /// </summary> bool isCheck = true; /// <summary> /// 枚举 /// </summary> public enum CheckStyle { style1 = 0, style2 = 1, style3 = 2, style4 = 3, style5 = 4, style6 = 5 }; public ButtonCheck() { InitializeComponent(); //设置Style支持透明背景色并且双缓冲 this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); this.SetStyle(ControlStyles.DoubleBuffer, true); this.SetStyle(ControlStyles.ResizeRedraw, true); this.SetStyle(ControlStyles.Selectable, true); this.SetStyle(ControlStyles.SupportsTransparentBackColor, true); this.SetStyle(ControlStyles.UserPaint, true); this.BackColor = Color.Transparent; this.Cursor = Cursors.Hand; this.Size = new Size(87, 27); } /// <summary> /// 是否选中 /// </summary> public bool Checked { set { isCheck = value; this.Invalidate(); } get { return isCheck; } } CheckStyle checkStyle = CheckStyle.style1; /// <summary> /// 样式 /// </summary> public CheckStyle CheckStyleX { set { checkStyle = value; this.Invalidate(); } get { return checkStyle; } } protected override void OnPaint(PaintEventArgs e) { Bitmap bitMapOn = null; Bitmap bitMapOff = null; if (checkStyle == CheckStyle.style1) { bitMapOn = Properties.Resources.on1; bitMapOff = Properties.Resources.off1; } else if (checkStyle == CheckStyle.style2) { bitMapOn = Properties.Resources.on2; bitMapOff = Properties.Resources.off2; } else if (checkStyle == CheckStyle.style3) { bitMapOn = Properties.Resources.on3; bitMapOff = Properties.Resources.off3; } else if (checkStyle == CheckStyle.style4) { bitMapOn = Properties.Resources.on4; bitMapOff = Properties.Resources.off4; } else if (checkStyle == CheckStyle.style5) { bitMapOn = Properties.Resources.on5; bitMapOff = Properties.Resources.off5; } else if (checkStyle == CheckStyle.style6) { bitMapOn = Properties.Resources.on6; bitMapOff = Properties.Resources.off6; } Graphics g = e.Graphics; Rectangle rec = new Rectangle(0, 0, this.Size.Width, this.Size.Height); if (isCheck) { g.DrawImage(bitMapOn, rec); } else { g.DrawImage(bitMapOff, rec); } } //特别说明:ButtonCheck_Click这个事件要添加控制方法产生,而不是直接在这里写 private void ButtonCheck_Click(object sender, EventArgs e) { isCheck = !isCheck; this.Invalidate(); }
2.1.在用户控件后台写入上述代码
2.2.为用户控件添加点击事件
private void ButtonCheck_Click_1(object sender, EventArgs e) { isCheck = !isCheck; this.Invalidate(); }
第三步、调用自定义的开关按钮控件
3.1.项目上右击,点击重新生成
3.2.回到UI设计界面,刷新“工具箱”,会发现多出一个可使用的ButtonCheck控件
直接拖出来就可以使用自定义的开关按钮控件了
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!