Search code examples
c#convertersargb

How long value convert into ARGB color?


public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{ 
    string userColourString = value.ToString();
    Debug.WriteLine(userColourString);
    long userColourNumeric = 0; 
    Int64.TryParse(userColourString, out userColourNumeric); 
    var colourToUse = userColourNumeric;
    return (Color)ColorConverter.ConvertFromString(string.Format("#{0:x6}", colourToUse));
}

I'm trying to convert the following two values into colours by using the converter method above but it's not working,. -2147483630 16777215


Solution

  • The value 16777215 decimal converts to FFFFFF hexadecimal. I tested your code, and the value of colourToUse is indeed "#ffffff". That will easily convert to the color White.

    The value -2147483630 decimal ends up being converted to FFFFFFFF80000012 hexadecimal. I'm not sure what color you're hoping that'll convert to. No wonder the ConvertFromString method throws a format exception.


    You added that you're referencing an old chart of VB6 color constants.

    In order to generate the colors in that chart, you'll need to use ColorTranslator.FromWin32:

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var userColourString = value.ToString();
        int userColourNumeric = 0;
        int.TryParse(userColourString, out userColourNumeric);
        var colourToUse = userColourNumeric;
        return ColorTranslator.FromWin32(colourToUse);
    }