Color Picker Dropdown using C#

Posted by & filed under .Net.

While playing around one of hobby project, I found there is a nice color picker dropdown available in WordPad, for setting the font color. I was using Windows

Color Dialog. So I thought of implementing a WordPad like color picker. And I think I almost readed my goal. I need to try this in the Toolstrip dropdown too.

//On the Form load I am loading the colors to the Dropdown.
//You can also bind the p to the Dropdown.
Type t = typeof(Color);
PropertyInfo[] p = t.GetProperties();
foreach (PropertyInfo item in p)
{
    if (item.PropertyType.FullName.Equals("System.Drawing.Color", StringComparison.CurrentCultureIgnoreCase))
    {
        this.comboBox1.Items.Add(item.Name);
    }
}

And I set the Dropdown’s DrawMode property to “OwnerDrawFixed”. And in the DrawItem event of the Dropdown I wrote the code.

if (e.Index != -1)
{
    e.DrawBackground();
    e.Graphics.FillRectangle(GetCurrentBrush(comboBox1.Items[e.Index].ToString()), e.Bounds);
    Font f = comboBox1.Font;
    e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), f, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
    e.DrawFocusRectangle();
}

And the GetCurrentBrush() function returns the Brush for painting the rectangle. You can write the code in the DrawItem event too, but initialy I thought about setting the font color using the same color. But later that idea changed.

private Brush GetCurrentBrush(string colorName)
{
    return new SolidBrush(Color.FromName(colorName));
}

One issue I found in this code is, for black color, I can’t see the color name. And here is the screenshot of Color Picker Dropdown running on my machine.

Color Picker Dropdown screenshot

Color Picker Dropdown screenshot

4 Responses to “Color Picker Dropdown using C#”

  1. listener

    if (comboBox1.Items[e.Index].ToString() == “Black”)
    {
    Font f = this.Font;
    e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), f, Brushes.White, e.Bounds, StringFormat.GenericDefault);
    }

    Removes black on black issue. You can test it with an array of colors also.

    Reply
  2. RockStarInTraining

    You could also use a conditional to handle this in a single line of code

    e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), f, comboBox1.Items[e.Index].ToString() != “Black” ? Brushes.Black : Brushes.White, e.Bounds, StringFormat.GenericDefault);

    Reply

Leave a Reply

CAPTCHA Image
*