1、创建用户控件(Window窗体)
在控件库中添加用户控件(Window窗体),并命名为ColorCheckBox;
在属性/布局栏将Size设置为80,18。
2、修改ColorCheckBox代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UcLib
{
[DefaultEvent("CheckedChanged")]
public partial class ColorCheckBox : UserControl
{
public ColorCheckBox()
{
InitializeComponent();
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.MouseDown += ColorCheckBox_MouseDown;
CheckBoxColor = Color.Blue;
Checked=false;
Texts = "CheckBox";
}
private void ColorCheckBox_MouseDown(object sender, MouseEventArgs e)
{
Checked = !Checked;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
var g = e.Graphics;
g.SmoothingMode=SmoothingMode.AntiAlias;
SolidBrush solidBrush = new SolidBrush(this.checkBoxColor);
g.FillRectangle(solidBrush, new Rectangle(0, 0, 12, 12));
if(Checked)
{
Pen pen = new Pen(Color.White, 2.0f);
g.DrawLine(pen, 2, 3, 6, 8);
g.DrawLine(pen, 6, 8, 10, 2);
}
g.DrawString(this.Texts, new Font("Yahei", 10f), new SolidBrush(Color.Black), 18, 0);
}
#region Properties
private Color checkBoxColor;
[Description("选框颜色"), Category("自定义")]
public Color CheckBoxColor
{
get { return checkBoxColor; }
set { checkBoxColor = value; Refresh(); }
}
private bool mchecked;
[Description("是否选中"), Category("自定义")]
public bool Checked
{
get { return mchecked; }
set {
mchecked = value;
Refresh();
if (CheckedChanged != null)
{
CheckedChanged(this, null);
}
}
}
private string mText;
[Description("文本内容"), Category("自定义")]
public string Texts
{
get { return mText; }
set { mText = value; Refresh(); }
}
#endregion
#region Events
[Description("选中改变事件"), Category("自定义")]
public event EventHandler CheckedChanged;
#endregion
}
}