How can I extract the list of colors in the System.Drawing.Color struct into a collection or array?
Is there a more efficient way of getting a collection of colors than using this struct as a base?
How can I extract the list of colors in the System.Drawing.Color struct into a collection or array?
Is there a more efficient way of getting a collection of colors than using this struct as a base?
In System.Drawing there is an Enum KnownColor, it specifies the known system colors.
List<>: List allColors = new List(Enum.GetNames(typeof(KnownColor)));
Array[] string[] allColors = Enum.GetNames(typeof(KnownColor));
So you'd do:
string[] colors = Enum.GetNames(typeof(System.Drawing.KnownColor));
... to get an array of all the collors.
Or... You could use reflection to just get the colors. KnownColors includes items like "Menu", the color of the system menus, etc. this might not be what you desired. So, to get just the names of the colors in System.Drawing.Color, you could use reflection:
Type colorType = typeof(System.Drawing.Color);
PropertyInfo[] propInfoList = colorType.GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public);
foreach (System.Reflection.PropertyInfo c in propInfoList) {
Console.WriteLine(c.Name);
}
This writes out all the colors, but you could easily tailor it to add the color names to a list.
Chekc out this Code Project project on building a color chart.
Try this:
foreach (KnownColor knownColor in Enum.GetValues(typeof(KnownColor)))
{
Trace.WriteLine(string.Format("{0}", knownColor));
}
In addition to what jons911 said, if you only want the "named" colors and not the system colors like "ActiveBorder", the Color
class has an IsSystemColor property that you can use to filter those out.
Here is an online page that shows a handy swatch of each color along with its name.
You'll have to use reflection to get the colors from the System.Drawing.Color struct.
System.Collections.Generic.List<string> colors =
new System.Collections.Generic.List<string>();
Type t = typeof(System.Drawing.Color);
System.Reflection.PropertyInfo[] infos = t.GetProperties();
foreach (System.Reflection.PropertyInfo info in infos)
if (info.PropertyType == typeof(System.Drawing.Color))
colors.Add(info.Name);
This example shows how to get a list of the actual Color objects if you are looking to work with more than just the name.
Most of the answers here result in a collection of color names (strings) instead of System.Drawing.Color objects. If you need a collection of actual system colors, use this:
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
...
static IEnumerable<Color> GetSystemColors() {
Type type = typeof(Color);
return type.GetProperties().Where(info => info.PropertyType == type).Select(info => (Color)info.GetValue(null, null));
}