Samip Pokharel
Samip Pokharel

Reputation: 51

Converting Colour Name to Hex in C#

I wrote a program to get Color from the ColorDialogBox and convert it into Hex value using ColorTranslator.ToHtml but then it doesn't return Hex value instead it returns the solid color name . Any way to fix this ?

Here's my code :

   private void chooseClr_Click(object sender, EventArgs e) {

      colorDialog1.ShowDialog();
      Color checking = colorDialog1.Color;
      string hexColor = ColorTranslator.ToHtml(checking);
      MessageBox.Show(hexColor);
    }

Upvotes: 3

Views: 5747

Answers (2)

c0rd
c0rd

Reputation: 1419

This converts a color into a hex string

MessageBox.Show((colorDialog1.Color.ToArgb() & 0x00FFFFFF).ToString("X6"));

Upvotes: 2

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

It returns solid color name, if it is a valid HTML color.
If your color is custom (has no HTML name), then it returns HEX value.

As for me, the fastest and easiest solution is to write a custom function:

public static class HexColorExtensions
{
    public static string ToHex(this Color c) => $"#{c.R:X2}{c.G:X2}{c.B:X2}";
}

Now, you can simply use it this way:

Console.WriteLine(Color.Green.ToHex()); // #008000
Console.WriteLine(Color.Black.ToHex()); // #000000
Console.WriteLine(Color.FromArgb(1, 2, 3).ToHex()); // #010203

Upvotes: 8

Related Questions