C# Casting object to System.Drawing.Color

881 views Asked by At

I am trying to convert a color setting that is read from a registry key into System.Drawing.Color. I am casting the object that is returned from the registry to System.Drawing.Color, following this article: Convert OBJECT to System.Drawing.Color

System.Drawing.Color color = (System.Drawing.Color)result;

Here are a couple of examples of these registry values that I am getting as an object:

Type     Data
REG_SZ   Color [Olive]
REG_SZ   Color [A=255, R=255, G=128, B=128]

Casting the first registry key to System.Drawing.Color works fine, but when casting the second key, I get a "Specified cast is not valid" error. What is the best way to be able to cast both of these keys as System.Drawing.Color?

EDIT: I think the easiest way to solve this is when writing to the registry, I convert the Color to an ARGB (int32), that way when I read it I can just use Color.FromArgb (unless there is another solution I'm completely missing).

1

There are 1 answers

3
rajeemcariazo On BEST ANSWER

What you are getting from the registry could be a string so use ColorConverter class as suggested from this page

Here is a sample code:

Color regColor = (Color)ColorConverter.ConvertFromString((string)result);