c constructs the ColorComboBox of color drop down box

  • 2020-05-26 10:02:15
  • OfStack


    class ColorComboBox : ComboBox
    {
        /// <summary>
        ///  Current selected color 
        /// </summary>
        public Color SelectedColor
        {
            get { return Color.FromName(this.Text); }
        }
        /// <summary>
        ///  Constructor to construct a color drop-down list 
        /// </summary>
        public ColorComboBox()
        {
            this.DrawMode = DrawMode.OwnerDrawFixed;
            this.DropDownStyle = ComboBoxStyle.DropDownList;
            this.ItemHeight = 25;
            PropertyInfo[] propInfoList = typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public);
            foreach (PropertyInfo c in propInfoList)
            {
                this.Items.Add(c.Name);
            }
            this.Text = "Black"; // Set default color 
        }
        protected override void OnDrawItem(DrawItemEventArgs e)
        {
            Rectangle rect = e.Bounds;
            if (e.Index >= 0)
            {
                string colorName = this.Items[e.Index].ToString();
                Color c = Color.FromName(colorName);
                using (Brush b = new SolidBrush(c)) // Reserve drop-down space 
                {
                    e.Graphics.FillRectangle(b, rect.X, rect.Y + 2, rect.Width, rect.Height - 4);
                }
            }
        }


Related articles: