1

In Windows.Forms, I need to create a program which accepts any color and tries to find the corresponding system colors to it.

I was not able to figure out how to loop through all Colors of the System.Drawing.SystemColors class - it's a class, not an enum or a List.

How can I do this (some kind of reflection?)?

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
Ray
  • 7,940
  • 7
  • 58
  • 90
  • Indeed with reflection, let me see if I can cook something up. – SynerCoder Sep 08 '12 at 08:12
  • "corresponding system colors" - You can only use those? using [`Color.FromArgb()`](http://msdn.microsoft.com/en-us/library/system.drawing.color.fromargb.aspx) or any other `Color` conversion, you can use any existing color... – balexandre Sep 08 '12 at 08:18
  • You might wanna have a look here: http://stackoverflow.com/questions/3821174/c-sharp-getting-all-colors-from-color or here: http://stackoverflow.com/questions/4834659/c-sharp-loop-through-all-colors and one more: http://www.c-sharpcorner.com/UploadFile/mahesh/how-to-load-all-colors-in-a-combobox-using-C-Sharp/ Hope it helps. – avi.tavdi Sep 08 '12 at 08:18

2 Answers2

3

How about

public static Dictionary<string,object> GetStaticPropertyBag(Type t)
{
    const BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

    var map = new Dictionary<string, object>();
    foreach (var prop in t.GetProperties(flags))
    {
        map[prop.Name] = prop.GetValue(null, null);
    }
    return map;
}

or

foreach (System.Reflection.PropertyInfo prop in typeof(SystemColors).GetProperties())
{
     if (prop.PropertyType.FullName == "System.Drawing.Color")
         ColorComboBox.Items.Add(prop.Name);
}
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
1

And I cooked something up.

var typeToCheckTo = typeof(System.Drawing.Color);
var type = typeof(System.Drawing.SystemColors);
var fields = type.GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public).Where(p => p.PropertyType.Equals(typeToCheckTo));
foreach (var field in fields)
{
    Console.WriteLine(field.Name + field.GetValue(null, null));
}
SynerCoder
  • 12,493
  • 4
  • 47
  • 78
  • Thanks, I'm already using the solution above, but however, just one question about this one: To me, it looks like he is going through all the standard colors, not the special system colors (the ones like "GradientActiveCaption", "GrayText", "ButtonFace" etc.) which I need? – Ray Sep 08 '12 at 08:39
  • I now check all the `System.Drawing.SystemColors`, and only the static properties that are of type `System.Drawing.Color` using linq. So you need to add `using System.Linq;` at the top of your document. – SynerCoder Sep 08 '12 at 08:45