How would I specify a color in app.config and then convert that into an actual System.Drawing.Color object at runtime?
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.
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
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.
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"]);
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()
}
}
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.