Search code examples
c#arrayscollectionsloopscolors

C# getting all colors from Color


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.


Solution

  • 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);
    }