Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Converting delphi TColor to color (Hex)

enter image description here

These numbers are stored in the Database. They origionate from Delphi code. Although I assume they follow some kind of standard. I have tried Color.FromArgb(255);

But i know for a fact that the first is RED (in the delphi side), where as in ASP.NET it thinks its blue Color [A=0, R=0, G=0, B=255]

I want these numbers into Hexidecimal anyway. I.e. #000000 , #FFFF99 etc etc

Anyone know how to conver these Integers (see DB Picture) to Hexidecimal.

like image 735
IAmGroot Avatar asked Nov 29 '11 17:11

IAmGroot


1 Answers

Delphi colors (TColor) are XXBBGGRR when not from a palette or a special color.

See this article for more detail on the format (And other special cases). The article pointed by Christian.K also contains some details on the special cases.

Standard colors

To convert to a standard color you should use something like :

var color = Color.FromArgb(0xFF, c & 0xFF, (c >> 8) & 0xFF, (c >> 16) & 0xFF);

To convert to hex, :

string ColorToHex(Color color)
{
    return string.Format("#{0:X2}{1:X2}{2:X2}",
        color.R, color.G, color.B);
}

System colors

For system colors (negative values in your database), they are simply the windows constants masked by 0x80000000.

Thanks to David Heffernan for the info.

Sample code

Color DelphiColorToColor(uint delphiColor)
{
    switch((delphiColor >> 24) & 0xFF)
    {
        case 0x01: // Indexed
        case 0xFF: // Error
            return Color.Transparent;

        case 0x80: // System
            return Color.FromKnownColor((KnownColor)(delphiColor & 0xFFFFFF));

        default:
            var r = (int)(delphiColor & 0xFF);
            var g = (int)((delphiColor >> 8) & 0xFF);
            var b = (int)((delphiColor >> 16) & 0xFF);
            return Color.FromArgb(r, g, b);
    }
}

void Main()
{
    unchecked
    {
        Console.WriteLine(DelphiColorToColor((uint)(-2147483646)));
        Console.WriteLine(DelphiColorToColor(
                (uint)KnownColor.ActiveCaption | 0x80000000
            ));
        Console.WriteLine(DelphiColorToColor(0x00FF8000));
    }
}
like image 94
Julien Roncaglia Avatar answered Sep 23 '22 19:09

Julien Roncaglia