指定したコントロールにフォーカスがあるときラベルを強調 2

ラベルの強調表示の解除と強調の方法を指定できるようにした。

■使用例

  //強調(デフォルト設定)
  LabelHighlighter.Add(label1, textBox1);

  //強調の解除
  LabelHighlighter.Remove(label1, textBox1);

  //強調(強調方法を指定)
  LabelHighlighter.Add(label1, textBox1, lb => lb.ForeColor = Color.Red);

ラベル強調.png

■コード

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace SabineLib.WindowsForms
{
  /// <summary>
  /// ラベルの強調設定をするクラス。
  /// </summary>
  public class LabelHighlighter
  {
    class Setting
    {
      public Label Label { get; set; }
      public Control Control { get; set; }
      public EventHandler Enter { get; set; }
      public EventHandler Leave { get; set; }
    }

    static List<Setting> settings = new List<Setting>();

    /// <summary>
    /// 指定したコントロールにフォーカスがあるとき、ラベルを強調。
    /// </summary>
    /// <param name="label">強調するラベル</param>
    /// <param name="control">フォーカスを監視するコントロール</param>
    /// <param name="highlighter">強調の方法</param>
    public static void Add(Label label, Control control, 
      Action<Label> highlighter = null)
    {
      if (label == null || control == null)
      {
        return;
      }

      Remove(label, control);

      var s = new Setting();
      s.Label = label;
      s.Control = control;

      try
      {
        s.Enter = (sender, e) =>
        {
          if (highlighter == null)
          {
            SetHighlight(label);
          }
          else
          {
            highlighter(label);
          }
        };
        control.Enter += s.Enter;

        s.Leave = (sender, e) =>
        {
          SetNormal(label);
        };
        control.Leave += s.Leave;

        settings.Add(s);
      }
      catch
      {
        if (s.Enter != null)
        {
          control.Enter -= s.Enter;
        }

        if (s.Leave != null)
        {
          control.Leave -= s.Leave;
        }

        throw;
      }
    }

    /// <summary>
    /// 強調設定の解除。
    /// </summary>
    public static void Remove(Label label, Control control)
    {
      var list = settings.FindAll(i =>
        i.Label == label && i.Control == control);
      foreach (var item in list)
      {
        SetNormal(label);
        item.Control.Enter -= item.Enter;
        item.Control.Leave -= item.Leave;
        settings.Remove(item);
      }
    }

    static void SetHighlight(Label label)
    {
      label.Font = new Font(label.Font.FontFamily, label.Font.Size, 
        FontStyle.Bold | FontStyle.Underline);
      label.ForeColor = Color.Blue;
    }

    static void SetNormal(Label label)
    {
      label.Font = new Font(label.Font.FontFamily, label.Font.Size);
      label.ForeColor = SystemColors.ControlText;
    }
  }
}