Home > .NET 2.0, C# 2.0 > Using the KnownColor Enum

Using the KnownColor Enum

May 4, 2007

DOWNLOAD THE CODE

I was recently searching for a color to use as a warning color for one of my apps. Basically, when the user entered a particular state in the application, I wanted to change the background of a panel to something unusual so they would immediately see that something had changed. While I ended up using standard Color.Red, I don’t really like it (and it washes out something onthe panel that is already red). So I was looking through the named colors in Visual Studio, and more than a little frustrated that I didn’t know what some of the colors really were.

So I got to thinking that a it might be handy to have a utility that would let me scroll through the System names and see the colors. So I took a few mintues, spent a little time on the Internet, and popped out a SystemColorChooser. It’s a really simple form:

And if you change one or both of the drop downs, you immediately see the results:

Finding the Magic

The magic in this is the System.Drawing.KnownColor Enum. In it is a list of all the color names you see listed in Visual Studio. I used the code I supplied previously to loop through the Enum and populate the ComboBoxes. I then cast the selected values and used them to set the rightside panel’s color values based on the selections:

private void cboxBackgroundColor_SelectedIndexChanged(object sender, EventArgs e)
{
    this.splitContainer1.Panel2.BackColor = Color.FromKnownColor((KnownColor)Enum.Parse(typeof(KnownColor), this.cboxBackgroundColor.SelectedItem.ToString()));
}

private void cboxTextColor_SelectedIndexChanged(object sender, EventArgs e)
{
    this.splitContainer1.Panel2.ForeColor = Color.FromKnownColor((KnownColor)Enum.Parse(typeof(KnownColor), this.cboxTextColor.SelectedItem.ToString()));
}

Now I have a simple way to select colors based on their System Names.

Advertisements
Categories: .NET 2.0, C# 2.0
  1. Patrick A
    June 14, 2010 at 1:55 pm

    Very helpful. Do you know of an easy way to “trim down” the list so that it does not show the “non-color” colors like ActiveBorder, etc? I just want to see colors like “aqua”, etc.

  1. No trackbacks yet.
Comments are closed.
%d bloggers like this: