⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 class1.cs

📁 通过重写C#中的ComboBox类
💻 CS
字号:
using System;
using System.Drawing;
using System.Windows.Forms;

namespace CustomColoredComboBox
{
    class ColoredComboBox : ComboBox
    {
        private  string[] arr_MyColors = { "Black", "Red", "Blue", "Green" };  //the default colors from list
        protected int inMargin;  
        protected int boxWidth;
        private Color c;

        public string[] MyColors  //public proprties to interact with control from proprties window
        {
            get { return arr_MyColors; }
            set 
            {
                int col_numbers = value.Length;
                arr_MyColors = new string[col_numbers];
                for (int i = 0; i < col_numbers; i++)
                    arr_MyColors[i] = value[i];
                this.Items.Clear();
                InitCombo();
            }
        }
        public ColoredComboBox()  //constructor
        {
            DrawMode = DrawMode.OwnerDrawFixed;
            DropDownStyle = ComboBoxStyle.DropDownList;
            inMargin = 2;
            boxWidth = 3;
            BeginUpdate();
            InitCombo();
            EndUpdate();
        }

        private void InitCombo() //add items 
        {
            if (arr_MyColors == null) return;
            foreach (string color in arr_MyColors)
            {
                try
                {
                    if (Color.FromName(color).IsKnownColor)
                        this.Items.Add(color);
                }
                catch 
                {
                    throw new Exception("Invalid Color Name: " + color);
                }
            }
        }
        
        protected override void OnDrawItem(DrawItemEventArgs e)
        {
            base.OnDrawItem(e);
            if ((e.State & DrawItemState.ComboBoxEdit) != DrawItemState.ComboBoxEdit)
                e.DrawBackground();

            Graphics g = e.Graphics;
            if (e.Index == -1)  //if index is -1 do nothing
                return;
            c = Color.FromName((string)base.Items[e.Index]);

            //the color rectangle
            g.FillRectangle(new SolidBrush(c), e.Bounds.X + this.inMargin, e.Bounds.Y + this.inMargin, e.Bounds.Width / this.boxWidth - 2 * this.inMargin, e.Bounds.Height - 2 * this.inMargin);
            //draw border around color rectangle
            g.DrawRectangle(Pens.Black, e.Bounds.X + this.inMargin, e.Bounds.Y + this.inMargin, e.Bounds.Width / this.boxWidth - 2 * this.inMargin, e.Bounds.Height - 2 * this.inMargin);
            //draw strings
            g.DrawString(c.Name, e.Font, new SolidBrush(ForeColor), (float)(e.Bounds.Width / this.boxWidth + 5 * this.inMargin), (float)e.Bounds.Y);
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -