1.目的:
为了在winform中实现一个带指示灯的button按钮,每点击一次改变一下颜色,以表示按钮状态,类似如下图所示效果。
2.实现思路:
在一个用户控件上放一个button和一个圆形控件拼成想要的效果
3.实现步骤
(1)新建一个用户控件light,拖拽一个button到用户控件上并填充满整个界面。然后以label控件为基础重绘出一个圆形控件,拖拽到button上。
圆形标签类代码如下:
public class CircleLabel : Label//继承标签类 重新生成解决方案就能在工具箱出现
{
protected override void OnPaint(PaintEventArgs e)//重新设置控件的形状 protected 保护 override重新
{
base.OnPaint(e);//递归 每次重新都发生此方法,保证其形状为自定义形状
System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
path.AddEllipse(2, 2, this.Width - 6, this.Height - 6);
//Graphics g = e.Graphics;
//g.DrawEllipse(new Pen(Color.Red, 2), 2, 2, Width - 6, Height - 6);
Region = new Region(path);
}
}
(2)在light下声明文本与指示灯颜色属性
private string buttonText;
public string ButtonText {
get { return buttonText; }
set {
if (buttonText != value) {
buttonText = value;
if (this.button1!= null) {
button1.Text = " " + this.ButtonText;
}
}
}
}
private Color circleColor;
public Color CircleColor {
get { return circleColor; }
set {
if (circleColor != value) {
circleColor = value;
circleLabel.BackColor = this.CircleColor;
}
}
}
(3)在button的点击事件中实现点击切换指示灯颜色:
private void button1_Click(object sender, EventArgs e)
{
if(circleLabel.BackColor == Color.FromArgb(64, 202, 33)) {
circleLabel.BackColor = Color.FromArgb(128, 128, 128);
}
else {
circleLabel.BackColor = Color.FromArgb(64, 202, 33);
}
OnCustomControlClicked();
}
(4)这个时候重新生成一下解决方案,自定义的Light按钮就出现在工具箱了,然后把它拖到我们想要使用的地方(例如form1界面),点击按钮以后就可以切换颜色了。但这里要注意在点击自定义控件Light时触发的是自定义控件Light内button的click事件,如果想要在form1后台编写自定义控件Light的click事件,需要自定义事件,代码如下:
在light后台定义事件:
public event EventHandler CustomControlClicked;
protected virtual void OnCustomControlClicked()
{
CustomControlClicked?.Invoke(this, EventArgs.Empty);
}
然后在light的事件列表中就可以看到CustomControlClicked事件了,直接可以双击进入
private void light1_CustomControlClicked(object sender, EventArgs e)
{
//编写代码
}
注意要在button1_Click事件中调用一下OnCustomControlClicked();
以上就是全部过程