3

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);
    }
4

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

Comments

2

This converts a color into a hex string

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.