aumanets
aumanets

Reputation: 3833

C# Create Instance of Color from any supported Format (Win.Forms Properties -> Color)

What is the best way to instantiate a new Color from any supported value, like for example "FF00FF11" or "Gray" or "234,255,65"? I need to generalize maximum as possible this implementation, but can't find a way to do it.

With System.Reflaction I can get the value for enumerator KnownColor, but how can I distinct this "FF00FF11" from this "Gray"?

Any help will be appreciated.

Upvotes: 1

Views: 250

Answers (2)

JDunkerley
JDunkerley

Reputation: 12505

When we need to do this we used the TypeConverter. The static function I used was:

    private static System.ComponentModel.TypeConverter colorConv = System.ComponentModel.TypeDescriptor.GetConverter(System.Drawing.Color.Red);

    /// <summary>
    /// Parse a string to a Color
    /// </summary>
    /// <param name="txt"></param>
    /// <returns></returns>
    public static System.Drawing.Color ColorFromString(string txt)
    {
        try
        {
            object tmp = colorConv.ConvertFromString(txt);
            return (tmp is System.Drawing.Color) ? (System.Drawing.Color)tmp : System.Drawing.Color.Empty;
        }
        catch 
        {
            // Failed To Parse String
            return System.Drawing.Color.Empty;
        }
    }

This works for two of your cases but fails on the Hex one. You could add some logic to try to parse the Hex one first.

Upvotes: 1

lc.
lc.

Reputation: 116528

You might want to take a look at System.Drawing.ColorTranslator.FromHtml(string).

I'm not sure it'll help you with your last example ("234,255,65"), however. You might have to try to parse that first (String.Split(), Int32.TryParse(), Color.FromArgb()) and if it fails, use the above.

Upvotes: 0

Related Questions