How To: Color Conversion in .NET

 

Ever heard of ColorTranslator? It's a really cool class that you can use to convert colors in .NET. One of the things that it can do is that enables you to convert HTML colors to Windows colors and vice versa. One particular scenario wherein you might want to use this class is when you want to use HTML colors on your WinForm.

Below are examples on how to use this calls:

using System;
using System.Drawing;
using System.Windows.Forms;

namespace ColorTranslatorTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //convert a system.drawing.color to html
            Color c1 = Color.AntiqueWhite;
            button1.BackColor = c1;
            button1.Text = ColorTranslator.ToHtml(c1);

            //convert an html color to a gdi+ color
            string htmlColor = "#FFAD55";
            Color c2 = ColorTranslator.FromHtml(htmlColor);
            button2.BackColor = c2;
            button2.Text = ColorTranslator.ToHtml(c2);

            //convert a win32 color to gdi+ color
            int colorHexadecimalValue = 0xA267;
            Color c3 = ColorTranslator.FromWin32(colorHexadecimalValue);
            button3.BackColor = c3;
            button3.Text = ColorTranslator.ToWin32(c3).ToString("X");
        }
    }
}

HTH


Posted Sep 05 2008, 10:33 AM by keithrull

Add a Comment

(required)  
(optional)
(required)  
Remember Me?

Enter the numbers above:

Copyright DevPinoy 2005-2008