UserControl のキャプション用ラベル

UserControl のキャプションとして使うラベル。

  • 親コントロール内にフォーカスがあるかないかで、背景色を変える。
  • 背景色は、グラデーションで表示する。
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace HeaderedContent
{
    internal class CaptionLabel : Label
    {
        private const LinearGradientMode GradientMode = LinearGradientMode.Horizontal;

        private Color StartColor
        {
            get
            {
                if (Parent.ContainsFocus)
                {
                    return SystemColors.GradientActiveCaption;
                }
                else
                {
                    return SystemColors.GradientInactiveCaption;
                }
            }
        }

        private Color EndColor
        {
            get
            {
                if (Parent.ContainsFocus)
                {
                    return SystemColors.ActiveCaption;
                }
                else
                {
                    return SystemColors.InactiveCaption;
                }
            }
        }

        protected override void OnPaintBackground(PaintEventArgs pevent)
        {
            Graphics g = pevent.Graphics;
            Rectangle rect = new Rectangle(0, 0, Width, Height);

            using (var brush = new LinearGradientBrush(rect, StartColor, EndColor, GradientMode))
            {
                g.FillRectangle(brush, rect);
            }
        }
    }
}

表示はこんなふうになる。

f:id:tt195361:20150520133552p:plain

参考: Simple Label Gradient