C# label 底線方式自行修改寬度

C# label 底線顯示方式可自行修改寬度

先加入元件列別為MyLable或自定義名稱

再將以下code加入

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MemDevlopTool
{
    public partial class MyLabel : Label
    {
        private Color mBorderColor = Color.Gray;
        private int mLineWidth = 3;

        [Browsable(true), Description("底框顏色"), Category("自定義分組")]
        public Color BorderColor
        {
            get { return mBorderColor; }
            set { mBorderColor = value; }
        }
        [Browsable(true), Description("底框厚度"), Category("自定義分組")]
        public int LineWidth
        {
            get { return mLineWidth; }
            set { mLineWidth = value; }
        }
        public MyLabel()
        {
            InitializeComponent();
        }

        public MyLabel(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
            //可自行定義初始化方式
            this.BackColor = GlobalVariable.BackColor;//背景
            this.Font = new Font("Calibri", 12F);//字型
            this.ForeColor = GlobalVariable.ForeColor;//字體顏色
        }

        // 重寫顯示方式
        protected override void OnPaint(PaintEventArgs e)
        {
            var vSize = e.Graphics.MeasureString(this.Text, this.Font);
            e.Graphics.Clear(this.BackColor);
            
            Pen vPen = new Pen(this.mBorderColor); // 用屬性顏色來畫邊框顏色
            SolidBrush linecolor = new SolidBrush(this.mBorderColor);
            e.Graphics.FillRectangle(linecolor, new Rectangle(0, this.Height - this.mLineWidth, this.Width, this.mLineWidth));繪製下方底線

            Rectangle rect1 = new Rectangle(0, 0, this.Width, this.Height);
            TextFormatFlags flags = TextFormatFlags.HorizontalCenter |
            TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak;
            TextRenderer.DrawText(e.Graphics, this.Text, this.Font, rect1, this.ForeColor, flags);
        }
    }
}

在使用MyLabel control來加入winform

 

效果如下