Color Picker Dropdown using C#
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
