萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 自訂控制項:ColorComboBox 下拉式顏色選擇器實作

需求場景

WinForms 專案常需讓使用者從預定義顏色中選擇。標準 ComboBox 僅顯示文字,若能直接在下拉清單顯示**顏色色塊**,使用體驗將大幅提升。本文實作繼承 ComboBox 的 ColorComboBox,自動載入 System.Drawing.Color 所有靜態屬性顏色,並支援 OwnerDraw 繪製色塊。

完整程式碼

using System;
using System.ComponentModel;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;

namespace CustomControls
{
    /// 
    /// 下拉式顏色選擇器:自動列舉 Color 靜態屬性,OwnerDraw 繪製色塊。
    /// 
    [ToolboxItem(true)]
    [DefaultProperty(nameof(SelectedColor))]
    public class ColorComboBox : ComboBox
    {
        // ------------------------------------------------------------
        // 公用屬性
        // ------------------------------------------------------------
        /// 目前選取的顏色(若 Text 非標準顏色名稱則回傳 Color.Empty)
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Color SelectedColor
        {
            get
            {
                try { return Color.FromName(Text); }
                catch { return Color.Empty; }
            }
            set
            {
                if (value == Color.Empty) { Text = string.Empty; return; }
                // 優先尋找已知顏色名稱
                foreach (PropertyInfo p in typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.Public))
                {
                    if (((Color)p.GetValue(null)).ToArgb() == value.ToArgb())
                    {
                        Text = p.Name;
                        return;
                    }
                }
                // 找不到名稱時以 ARGB 字串表示
                Text = $"#{value.R:X2}{value.G:X2}{value.B:X2}";
            }
        }

        // ------------------------------------------------------------
        // 建構函式:初始化樣式與填入顏色清單
        // ------------------------------------------------------------
        public ColorComboBox()
        {
            // OwnerDraw 固定模式
            DrawMode = DrawMode.OwnerDrawFixed;
            DropDownStyle = ComboBoxStyle.DropDownList; // 禁止自由輸入
            ItemHeight = 24; // 色塊高度

            // 反射取得 Color 所有 public static 唯讀屬性(KnownColor)
            var colorProps = typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public);
            foreach (var prop in colorProps)
            {
                if (prop.PropertyType == typeof(Color))
                    Items.Add(prop.Name);
            }

            // 預設選取 Black
            if (Items.Count > 0) SelectedIndex = Items.IndexOf("Black");
        }

        // ------------------------------------------------------------
        // OwnerDraw 繪製項目
        // ------------------------------------------------------------
        protected override void OnDrawItem(DrawItemEventArgs e)
        {
            base.OnDrawItem(e);

            if (e.Index < 0) return;

            string colorName = Items[e.Index].ToString();
            Color color = Color.FromName(colorName);

            // 背景
            e.DrawBackground();

            // 色塊區域:留白 2px 上下、4px 左右
            var rect = new Rectangle(e.Bounds.Left + 4, e.Bounds.Top + 2, e.Bounds.Height - 4, e.Bounds.Height - 4);
            using (var brush = new SolidBrush(color))
                e.Graphics.FillRectangle(brush, rect);

            // 色塊邊框
            using (var pen = new Pen(Color.Gray))
                e.Graphics.DrawRectangle(pen, rect);

            // 文字:色塊右側 8px 起
            var textRect = new Rectangle(rect.Right + 8, e.Bounds.Top, e.Bounds.Width - rect.Right - 12, e.Bounds.Height);
            TextRenderer.DrawText(e.Graphics, colorName, e.Font, textRect, e.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Left);

            // 焦點框
            e.DrawFocusRectangle();
        }
    }
}

核心實作細節

  1. 反射列舉顏色:typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public) 精準取得 141 個已知顏色,避免硬編碼。
  2. OwnerDrawFixed:固定項目高度,效能優於 OwnerDrawVariable。
  3. DropDownList:禁止使用者輸入任意字串,確保 SelectedColor 永遠可解析。
  4. SelectedColor 雙向綁定:Getter 解析 Text,Setter 反向匹配 ARGB 找回名稱,支援資料繫結。
  5. 繪製優化:使用 using 確保 Brush/Pen 即時釋放,避免 GDI 物件洩漏。

使用範例

// 設計師拖曳或動態建立
var colorBox = new ColorComboBox
{
    Location = new Point(20, 20),
    Width = 200
};
colorBox.SelectedColorChanged += (s, e) =>
{
    var box = (ColorComboBox)s;
    lblPreview.BackColor = box.SelectedColor;
    lblColorName.Text = box.Text;
};
this.Controls.Add(colorBox);

擴展建議

  • 最近使用顏色:在清單頂端插入「Recent Colors」分隔區,儲存使用者最近 10 次選擇。
  • 自訂調色盤:公開 AddCustomColor(Color c, string name) 方法,讓專案註冊品牌色。
  • 高 DPI 支援:ItemHeight 隨 DeviceDpi 縮放,繪製座標使用 e.Graphics.DpiX 計算。
  • 鍵盤搜尋:覆寫 OnKeyDown,輸入首字母快速跳轉。

結語

ColorComboBox 以 80 行核心程式碼,結合反射、OwnerDraw、資料繫結,打造出專業級顏色選擇器。同樣模式可擴展為 FontComboBox、IconComboBox 等豐富下拉控制項,是 WinForms 客製化開發的經典範本。

copyright © 萬盛學電腦網 all rights reserved