Ray
Ray

Reputation: 8844

List all SystemColors

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?)?

Upvotes: 1

Views: 3840

Answers (2)

SynerCoder
SynerCoder

Reputation: 12766

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

Upvotes: 1

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48558

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

Upvotes: 3

Related Questions