Simon Keep
Simon Keep

Reputation: 10002

How to specify a Colour in config

How would I specify a color in app.config and then convert that into an actual System.Drawing.Color object at runtime?

Upvotes: 3

Views: 4802

Answers (6)

Darren
Darren

Reputation: 961

Have a look at ColorTranslator. You'll be able to specify a color, say in appSettings and use ColorTranslator to convert it into a real color. In particular I've found the .FromHtml() method very useful.

Upvotes: 3

NotJarvis
NotJarvis

Reputation: 1247

You could just store the color as an int value, which can be serialised, and add a property of type color which uses toArgb and from argb to convert it.

e.g.

private ColorInt

public Color shapeColor
{
    get {
         return Color.FromArgb(ColorInt);
     }
      set 
    {
        ColorInt = value.toargb()
    }
}

Upvotes: 0

John Lemp
John Lemp

Reputation: 5067

You config would look like this:

<add key="SomethingsColor" value="Black" />

and you can convert it to a color:

Color myColor = Color.FromName(ConfigurationManager.AppSettings["KEY"]);

Upvotes: 2

Timothy Khouri
Timothy Khouri

Reputation: 31845

I wrote this article about custom config sections in ASP.NET... but the principal (and the code) is the same for the "app.config" (non web apps). But if that's overkill for you, then you could just convert the string as is mentioned by a few other people.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062512

Color is an oddity; regular xml-serialization doesn't normally work - hence you often need to add your own code, perhaps via TypeConverter:

static void Main()
{

    Test(Color.Red);
    Test(Color.FromArgb(34,125,75));
}
static void Test(Color color)
{
    TypeConverter converter = TypeDescriptor.GetConverter(typeof(Color));
    string s = converter.ConvertToInvariantString(color);
    Console.WriteLine("String: " + s);
    Color c = (Color) converter.ConvertFromInvariantString(s);
    Console.WriteLine("Color: " + c);
    Console.WriteLine("Are equal: " + (c == color));
}

Outputs:

String: Red
Color: Color [Red]
Are equal: True
String: 34, 125, 75
Color: Color [A=255, R=34, G=125, B=75]
Are equal: True

Upvotes: 2

Stu Mackellar
Stu Mackellar

Reputation: 11638

One way would be to specify one of the KnownColor values as the config text and then use Color.FromName to create the Color object.

Upvotes: 4

Related Questions