winform控件开发一之复合控件开发(5)指示灯(LED)
使用自定义控件,实现一个LED指示灯,显示效果如下:
该LED灯可以显示为圆形或椭圆形;
可以显示文字;
可以显示不同的颜色;
该LED灯的设计使用使用扩展控件的方法,通过对label标签进行扩展;
具体代码如下:
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace 各种C_sharp功能测试 { /// <summary> /// 一个Label扩展控件 /// 控件的形状为一个有边框的椭圆 /// </summary> public class LED : Label { public LED() { SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.ResizeRedraw, true); SetStyle(ControlStyles.SupportsTransparentBackColor, true); this.SizeChanged += OvalLabel_SizeChanged; } Rectangle rect; private void OvalLabel_SizeChanged(object sender, EventArgs e) { rect = new Rectangle(0, 0, this.Width, this.Height); this.Region = new Region(rect); rect.Width -= 1; rect.Height -= 1; } //边框宽度 private int borderWidth = 1; public int BorderWidth { get { return borderWidth; } set { borderWidth = value; Invalidate(); } } //边框颜色 private Color borderColor = Color.Black; public Color BorderColor { get { return borderColor; } set { borderColor = value; Invalidate(); } } //中心颜色 private Color centorColor = Color.LightGray; public Color CentorColor { get { return centorColor; } set { centorColor = value; Invalidate(); } } protected override void OnPaint(PaintEventArgs e) { //设置绘图区域 GraphicsPath path = new GraphicsPath(); path.AddEllipse(this.ClientRectangle); this.Region = new Region(path); //获取绘图对象 Graphics g = e.Graphics; //呈现质量设置为高质量 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;//HighQuality和AntiAlias执行效果相同 //获取边框内中心椭圆的矩形绘图区域 Rectangle innerRect = new Rectangle(rect.X + borderWidth, rect.Y + borderWidth, rect.Width - 2 * borderWidth, rect.Height - 2 * borderWidth); //填充边框 g.FillEllipse(new SolidBrush(borderColor), rect); //填充中心 g.FillEllipse(new SolidBrush(CentorColor), innerRect); this.AutoSize = false; this.BackColor = Color.Transparent; this.TextAlign = ContentAlignment.MiddleCenter; base.OnPaint(e); } } }
分类:
winform控件开发
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~