2

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);
    }
  • 2
    Perhaps you should try reading the [`ColorTranslator.ToHtml` documentation](https://msdn.microsoft.com/en-us/library/system.drawing.colortranslator.tohtml(v=vs.110).aspx): "This method translates a Color structure to a string representation of an HTML color. This is the commonly used name of a color, such as "Red", "Blue", or "Green", and not string representation of a numeric color value, such as "FF33AA"." – Ian Kemp Aug 25 '16 at 05:46
  • Possible duplicate of [How to convert color name to the corresponding hexadecimal representation?](http://stackoverflow.com/questions/8336375/how-to-convert-color-name-to-the-corresponding-hexadecimal-representation) – j4rey Aug 25 '16 at 05:47
  • 2
    Possible duplicate of [Convert .Net Color Objects to HEX codes and Back](http://stackoverflow.com/questions/982028/convert-net-color-objects-to-hex-codes-and-back) – Ian Kemp Aug 25 '16 at 05:47
  • Possible duplicate of [Convert System.Drawing.Color to RGB and Hex Value](http://stackoverflow.com/questions/2395438/convert-system-drawing-color-to-rgb-and-hex-value) – Shaharyar Aug 25 '16 at 05:49

2 Answers2

6

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
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
2

This converts a color into a hex string

MessageBox.Show((colorDialog1.Color.ToArgb() & 0x00FFFFFF).ToString("X6"));
c0rd
  • 1,329
  • 1
  • 13
  • 20