Search code examples
c#colorsvisual-studio-2015hexcolor-picker

How to get the hex color code from a color dialog in visual studio?


I have a color dialog in visual studio, I am currently using this c# code to display the color dialog and set the color to a panel:

private void ColorButton_Click(object sender, EventArgs e)
{
    if (colorDialog1.ShowDialog() == DialogResult.OK)
    {
        ColorPanel.BackColor = colorDialog1.Color;
    }
}

How could I set a label to the hexadecimal color code of the color picker?


Solution

  • You can try this

    1. Get ARGB (Alpha, Red, Green, Blue) representation for the color
    2. Filter out Alpha channel: & 0x00FFFFFF
    3. Format out the value as hexadecimal ("X6")

    Implementation

      String code = (colorDialog1.Color.ToArgb() & 0x00FFFFFF).ToString("X6");
    

    Edit: if you want to get Color back from code, try FromArgb:

      string code = "FFDDAA";
    
      Color color = Color.FromArgb(Convert.ToInt32(code, 16));