在贴出代码之前,先看看所谓的自定义开关按钮。自己的项目中,需要切换网络还是本地,当切换为本地时加载属于本地内容的数据,反之网络。例如下方显示图,按正常情况下应该设置为两个按钮,分别为本地、网络,但是为了美观,我利用usercontrol控件作为按钮,根据点击状态来切换显示图片,同时执行不同状态的事件方法。
项目完整代码如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace SCommon { #region 枚举 public enum CheckStyle { 酒店 = 0, 开关 = 1 } #endregion public partial class YdButtonCheck : UserControl { #region 构造函数 public YdButtonCheck() { 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); } #endregion #region 属性 bool isCheck = false; [DefaultValue(false)] [Description("是否选中")] public bool Checked { set { isCheck = value; this.Invalidate(); } get { return isCheck; } } private CheckStyle _CheckButtnStyle = CheckStyle.开关; [Description("选择样式")] public CheckStyle CheckButtnStyle { get { return _CheckButtnStyle; } set { _CheckButtnStyle = value; this.Invalidate(); } } #endregion #region 重绘 protected override void OnPaint(PaintEventArgs e) { Bitmap bitMapOn = null; Bitmap bitMapOff = null; if (_CheckButtnStyle == CheckStyle.开关) { bitMapOn = Properties.Resources.btncheckon; bitMapOff = Properties.Resources.btncheckoff; } else if (_CheckButtnStyle == CheckStyle.酒店) { bitMapOn = Properties.Resources.HotelSystemon; bitMapOff = Properties.Resources.HotelSystemoff; } 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); } } #endregion #region 点击事件 private void YdButtonCheck_Click(object sender, EventArgs e) { isCheck = !isCheck; this.Invalidate(); } #endregion } } 你可以根据项目中的方法中适当修改,设计属于你想要的效果,在枚举中定义类型,同时设计两张不同状态的图片,这样看起来就像一个完美按钮。切换使用方法如:ydButtonCheck1.Checked == true ? "执行方法1" : "执行方法2"。