C#重绘一个点击带框框的Label控件

.NET
487
0
0
2022-04-11
标签   C#

首先从Label类继承一个类取名FocusLabel

public class FocusLabel :Label
{
    private bool m_ShowBorder = false;
    protected override void OnPaint(PaintEventArgs e)
    {
        if (m_ShowBorder)
        {
            Rectangle rect = this.ClientRectangle;
            rect = new Rectangle(rect.X, rect.Y, rect.Width - 1, rect.Height - 1);
            e.Graphics.DrawRectangle(new Pen(Color.Orange), rect);
        }
        base.OnPaint(e);
    }
    //重写Click事件 
    protected override void OnClick(EventArgs e)
    {
        base.OnClick(e);
        if (this.Parent != null)
        {
            foreach (Control ctrl in this.Parent.Controls)
            {
                if (ctrl is FocusLabel && ctrl != this)
                {
                    ((FocusLabel) ctrl).m_ShowBorder = false;
                    ctrl.Refresh();
                }
            }
        }
        this.m_ShowBorder = true;
        this.Refresh();
    }
}