ゲージ表示用の.NETフォーム コントロール

ゲージ表示用のコントロールをProgressBarをベースに作った。ProgressBarからの変更点は、

  • アニメーション表示しない
  • バーの色はForeColorで設定できる
  • ニュートラルの値(Neutral)を基準にプラスマイナスの表示
using System;
using System.Drawing;
using System.Windows.Forms;

namespace Utility
{
    class GaugeBar : ProgressBar
    {
        public GaugeBar()
        {
            // OnPaintイベントが発生するようにする
            // ダブルバッファリングを有効にする
            base.SetStyle(
                ControlStyles.UserPaint |
                ControlStyles.AllPaintingInWmPaint |
                ControlStyles.OptimizedDoubleBuffer,
                true);
        }

        // ニュートラル値
        private int m_Neutral = 0;
        public int Neutral
        {
            get
            {
                return m_Neutral;
            }
            set
            {
                m_Neutral = value;
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            Rectangle rec = e.ClipRectangle;
            Brush foreBrush = new SolidBrush(this.ForeColor);

            // 枠線描画
            if (ProgressBarRenderer.IsSupported)
            {
                ProgressBarRenderer.DrawHorizontalBar(e.Graphics, e.ClipRectangle);
            }

            // ニュートラル値の座標
            int neutral = 2 + (rec.Width - 4) * (m_Neutral - Minimum) / (Maximum - Minimum);

            // プラスの場合
            if (Value > m_Neutral)
            {
                int offset = Value - m_Neutral;
                int width = (rec.Width - 4) * offset / Maximum;
                int height = rec.Height - 4;
                e.Graphics.FillRectangle(foreBrush, neutral, 2, width, height);
            }
            // マイナスの場合
            else if (Value < m_Neutral)
            {
                int offset = m_Neutral - Value;
                int width = (rec.Width - 4) * offset / Maximum;
                int height = rec.Height - 4;
                e.Graphics.FillRectangle(foreBrush, neutral - width, 2, width, height);
            }

            // ニュートラルの線
            if (m_Neutral != Minimum)
            {
                e.Graphics.DrawLine(Pens.DarkGray, neutral, 1, neutral, rec.Height - 1);
            }
        }
    }
}