Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# getting all colors from Color

Tags:

I want to make a ComboBox filled with all the colors from System.Drawing.Color

But I can't seem to collect all the colors from that collection

I've already tried using a foreach to do the job like this:

foreach (Color clr in Color)      {       } 

But all I get is an error.

So how can I loop trough all the colors?

Any help will be appreciated.

like image 634
Pieter888 Avatar asked Sep 29 '10 11:09

Pieter888


2 Answers

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); } 
like image 82
Julien Hoarau Avatar answered Nov 12 '22 20:11

Julien Hoarau


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); 
like image 27
Konrad Rudolph Avatar answered Nov 12 '22 22:11

Konrad Rudolph