Click here to Skip to main content
15,563,054 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i tried to translate the textbox back color to hex code but it gives incorrect result. how can i get a correct result please help!!!!

when the background color isred it gives 0000ff and when it is blue it gives ff0000

What I have tried:

Color myColor2 = textBox27.BackColor;
int nColorWin2 = ColorTranslator.ToWin32(myColor2);
textBox27.Text = string.Format("{0:X6}", nColorWin2);
Updated 22-Jun-22 19:38pm

1 solution

Those are correct: the Color value is an ARGB value: eight bits each for the Opacity ("A" or the Alpha-channel), Red, Green, and Blue values. If you convert them to Win32 values (which use a RGB space without the Alpha channel) then you get what you see.

If you want to print Color values with opacity, then use the ToArgb method instead:
Color col1 = Color.Red;
Color col2 = Color.Green;
Color col3 = Color.Blue;
Color col4 = Color.White;
Color col5 = Color.Black;
Color col6 = Color.Lime;

Debug.WriteLine($"{col1} = {ColorTranslator.ToWin32(col1):X8}:{(int)col1.ToArgb():X8}");
Debug.WriteLine($"{col2} = {ColorTranslator.ToWin32(col2):X8}:{(int)col2.ToArgb():X8}");
Debug.WriteLine($"{col3} = {ColorTranslator.ToWin32(col3):X8}:{(int)col3.ToArgb():X8}");
Debug.WriteLine($"{col4} = {ColorTranslator.ToWin32(col4):X8}:{(int)col4.ToArgb():X8}");
Debug.WriteLine($"{col5} = {ColorTranslator.ToWin32(col5):X8}:{(int)col5.ToArgb():X8}");
Debug.WriteLine($"{col6} = {ColorTranslator.ToWin32(col6):X8}:{(int)col6.ToArgb():X8}");
Which gives you:
Color [Red] = 000000FF:FFFF0000
Color [Green] = 00008000:FF008000
Color [Blue] = 00FF0000:FF0000FF
Color [White] = 00FFFFFF:FFFFFFFF
Color [Black] = 00000000:FF000000
Color [Lime] = 0000FF00:FF00FF00
Note that Color.Lime is "All green" rather than Color.Green - I have no idea why, other than Lime is kinda too bright for practical use!
Share this answer
CPallini 23-Jun-22 7:47am    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900