Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
Markdown Monster - The Markdown Editor for Windows

Converting Windows Forms Colors to Web RGB string values


:P
On this page:

On a couple of occasions I’ve now had to create HTML colors from Windows RGB colors. Why you might ask? I have a couple of WinForms that are using the Web Browser control and I needed to match the colors of the theme into the HTML that gets dynamically created and rendered.

 

There are a couple of ways to do this:

 

string HeaderColor = "#" +

          SystemColors.InactiveCaption.ToArgb().ToString("x").Substring(2);

 

The above is reliable for all situations. If you are using Web Colors on your Windows Forms you can get their names like this:

string Color = cd.Color.ToKnownColor().ToString();

 

Note that this basically returns the name of the color in the same way you see it in the IDE (in fact this is likely what the IDE uses to let you select the colors). This means if you use a non-Web color like the InactiveCaption color you get the name of the color ie. InactiveCaption. But if you choose something like BlueSteel the value will be returned as BlueSteel which works both in WinForms and the Web.


The Voices of Reason


 

Gabe
June 13, 2004

# re: Converting Windows Forms Colors to Web RGB string values

Don't forget...
system.drawing.ColorTranslator.ToHtml(color)

Rick Strahl
June 13, 2004

# re: Converting Windows Forms Colors to Web RGB string values

Thanks Gabe. Didn't know that one existed actually.

Fluxtah
April 04, 2006

# re: Converting Windows Forms Colors to Web RGB string values

system.drawing.ColorTranslator.ToHtml(color) does not work the way I expected it to.

Response.Write(System.Drawing.ColorTranslator.ToHtml(Color.Red));

Displays 'Red' and not '#FF0000'

Not sure why

vijay kumar N
March 15, 2012

# re: Converting Windows Forms Colors to Web RGB string values

thanks Fluxtah.

ya it 's working..

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2025