C# getting all colors from Color
You could take color from KnownColor
KnownColor[] colors = Enum.GetValues(typeof(KnownColor));
foreach(KnownColor knowColor in colors)
{
Color color = Color.FromKnownColor(knowColor);
}
or use reflection to avoid color like Menu, Desktop... contain in KnowColor
Type colorType = typeof(System.Drawing.Color);
// We take only static property to avoid properties like Name, IsSystemColor ...
PropertyInfo[] propInfos = colorType.GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public);
foreach (PropertyInfo propInfo in propInfos)
{
Console.WriteLine(propInfo.Name);
}
Similar to @madgnome’s code, but I prefer the following since it doesn’t require parsing the string names (a redundant indirection, in my opinion):
foreach (var colorValue in Enum.GetValues(typeof(KnownColor)))
Color color = Color.FromKnownColor((KnownColor)colorValue);
My way to get colors. I think it is the best way via Reflection library.
private List<Color> GetAllColors()
{
List<Color> allColors = new List<Color>();
foreach (PropertyInfo property in typeof(Color).GetProperties())
{
if (property.PropertyType == typeof(Color))
{
allColors.Add((Color)property.GetValue(null));
}
}
return allColors;
}