winform 自定义 标签

本文介绍如何在Winform中创建自定义标签控件,包括实现带弧度的标签和关闭按钮的功能,并通过组合Label控件实现美观的查询标签显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

winform 标签

看一下效果
在这里插入图片描述
主要原因是winform 没有这样的标签控件,想要稍稍美化下程序,别的Express这些又要付费,用到的地方,主要是查询标签,显示类型等等。一通折腾自己搞一个。

首先分析一下

标签特点和组成:
1,带弧度
2,一个内容项
3,一个小叉叉 X

基本控件用啥,我用的是lable。
当然要是用Button 别的什么也可以,条条大路通罗马嘛。

那就是俩个带弧度的lable组合一下,搞成一个控件,一个显示内容,一个关闭事件。
在这里插入图片描述

带弧度的lable

新增一个组件(就这玩意)
在这里插入图片描述
继承Lable
看代码:

 public partial class RadiusLable : System.Windows.Forms.Label
 {
 	public RadiusLable()
        {
            InitializeComponent();
       }
        protected override void OnPaint(PaintEventArgs e)
        {
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            AddArcForm(this);
            base.OnPaint(e);
        }
        private void AddArcForm(System.Windows.Forms.Control form)
        {
            int basicWidth = 10;
            GraphicsPath p = new GraphicsPath();
            p.StartFigure();
            p.AddArc(new Rectangle(0, 0, basicWidth , basicWidth ), 180, 90);
            p.AddArc(new Rectangle(form.Width - basicWidth , 0, basicWidth , basicWidth ), 270, 90);
            p.AddArc(new Rectangle(form.Width - basicWidth , form.Height - basicWidth , basicWidth , basicWidth ), 0, 90);
            p.AddArc(new Rectangle(0, form.Height - basicWidth , basicWidth , basicWidth ), 90, 90);
            p.CloseFigure();
            form.Region = new Region(p);
        }
}

主要就是画那个弧度。别的功能根据需求重写。

组合控件

新建一个控件(就这玩意)
在这里插入图片描述
首先设计图,用到的是 一个panel 两个 字节重写的带弧度lable,按自己需求控制其大小,字体,颜色等。这儿就是弄一个简单的。
在这里插入图片描述
在这里插入图片描述
就搞这么大,根据需求调整。
lable 大小由自定义和自适用两种AutoSize 来控制,自使用太丑,所以就自定义了。给内容标签页赋值时自定义其大小,记得同时设置控件整体大小和panel大小。
再加一个关闭x的点击事件。搞一个对外事件,就完事了。
看代码

public partial class TagControl : UserControl
{
	public TagControl()
        {
            InitializeComponent();
        }
         [Description("关闭事件"), Category("自定义")]
        public event EventHandler CloseClick;
        public void SetText(string text)
        {
            this.Content.Text = text;
            if (text.Length > 2)
            {
                this.panel1.Width = 81 + (text.Length - 2) * 10;
                this.Width = 90 + (text.Length - 2) * 10;
                this.Content.Width = 76 + (text.Length - 2) * 10;            }
        }
        private void close_Click(object sender, EventArgs e)
        {
            CloseClick.Invoke(this, e);
        }
}

最终生成一下,其他界面调用就行了。
其中setText里设置的尺寸根据自己需求来。
代码很简短,一目了然。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值