Wednesday, 20 August 2014

Convert Hex / Css String color to .NET Colour (RGB)

Leave a Comment
Have you facing problem to convert "#CCCCCC" to .NET Colour.?

Here is a solution to convert the CSS / Hex String to .NET Colour (RGB).

Conversion Class

 
using System;
using System.Collections.Generic;
using System.Text;
using System;
using System.Drawing;
using System.Text.RegularExpressions;

namespace Convert_Hex_String_to.NET_Color
{

    public class ConversionClass
    {       

        /// <summary>
        /// Convert a hex string to a .NET Color object.
        /// </summary>
        /// <param name="hexColor">a hex string: "FFFFFF", "#000000"</param>
        public static Color HexStringToColor(string hexColor)
        {
            string hc = ExtractHexDigits(hexColor);
            if (hc.Length != 6)
            {
                // you can choose whether to throw an exception
                //throw new ArgumentException("hexColor is not exactly 6 digits.");
                return Color.Empty;
            }
            string r = hc.Substring(0, 2);
            string g = hc.Substring(2, 2);
            string b = hc.Substring(4, 2);
            Color color = Color.Empty;
            try
            {
                int ri
                   = Int32.Parse(r, System.Globalization.NumberStyles.HexNumber);
                int gi
                   = Int32.Parse(g, System.Globalization.NumberStyles.HexNumber);
                int bi
                   = Int32.Parse(b, System.Globalization.NumberStyles.HexNumber);
                color = Color.FromArgb(ri, gi, bi);
            }
            catch
            {
                // you can choose whether to throw an exception
                //throw new ArgumentException("Conversion failed.");
                return Color.Empty;
            }
            return color;
        }

        /// <summary>
        /// Extract only the hex digits from a string.
        /// </summary>
        public static string ExtractHexDigits(string input)
        {
            // remove any characters that are not digits (like #)
            Regex isHexDigit
               = new Regex("[abcdefABCDEF\\d]+", RegexOptions.Compiled);
            string newnum = "";
            foreach (char c in input)
            {
                if (isHexDigit.IsMatch(c.ToString()))
                    newnum += c.ToString();
            }
            return newnum;
        }

    }  

}


MessageBox Class

 
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace messageBox
{
    public static class MsgBox
    {
        // Displays a Confirm type message box
        // parameter name="sMsg" is The message you want to display
        public static bool Confirm(string sMsg)
        {
            return Confirm("Confirm :", sMsg);
        }
        public static bool Confirm(string sTitle, string sMsg)
        {
            DialogResult ret = MessageBox.Show(sMsg, sTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            return (ret == DialogResult.Yes);
        }

        //---------------------------------------------------------------------
        // Displays a Error type message box      
        // parameter name="sMsg" is The message you want to display
        public static void Error(string sMsg)
        {
            Error("Error :", sMsg);
        }
        public static void Error(string sTitle, string sMsg)
        {
            MessageBox.Show(sMsg, sTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        //---------------------------------------------------------------------
        // Displays a Warning type message box. parameter name="sMsg" is The message you want to display
        public static void Warning(string sMsg)
        {
            Warning("", sMsg);
        }

        //---------------------------------------------------------------------
        // Displays a Warning type message box       
        // parameter name="sCaption" is  Name of Application or Class or Method
        // parameter name="sMsg" is The message you want to display
        public static void Warning(string sCaption, string sMsg)
        {
            if (sCaption.Length == 0)
                sCaption = "Warning";
            MessageBox.Show(sMsg, sCaption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        //---------------------------------------------------------------------
        // Displays a Information type message box    
        // parameter name="sMsg" is The message you want to display
        public static void Info(string sMsg)
        {
            Info("", sMsg);
        }

        //---------------------------------------------------------------------
        // Displays a Information type message box       
        // parameter name="sCaption" is Name of Application or Class or Method
        // parameter name="sMsg" is The message you want to display
        public static void Info(string sCaption, string sMsg)
        {
            if (sCaption.Length == 0)
                sCaption = "Information";
            MessageBox.Show(sMsg, sCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

    }
}


Program Code Behind

 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using messageBox;

namespace Convert_Hex_String_to.NET_Color
{
    public partial class Form1 : Form
    {
        private string msAppName = "Convert CSS String color to .Net Color Class"; // Program Name

        public Form1()
        {
            InitializeComponent();     
        }

        public void TestHexStringToColor(string hexColor)
        {
            // invent some hex colors
            string[] h = new string[1];
            h[0] = hexColor;

            // convert the hex values to colors
            Color[] colors = new Color[4];
            colors[0] = ConversionClass.HexStringToColor(h[0]);

            // print the results
            Result.Text = "";
            for (int i = 0; i < h.Length; i++)
            {
                Result.Text += "\n" + h[i] + " =  "

                   + colors[i].Name + ", Red=" + colors[i].R.ToString()
                   + ", Green=" + colors[i].G.ToString()
                   + ", Blue=" + colors[i].B.ToString();                 

            }

        }
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MsgBox.Info("Thank You");
            this.Close();
        }

        private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            MsgBox.Info("Created By Mohd Zulkamal. - www.developersnote.com");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string hexColor = textBox1.Text.ToString();
            if (hexColor == "")
            {
                MsgBox.Info("Input was nothing");
                return;
            }
            else if (hexColor.Substring(0, 1) != "#")
            {
                MsgBox.Info("First Character must be \"#\"");
                return;
            }
            else
            {
                try
                {
                    TestHexStringToColor(textBox1.Text.ToString());
                }
                catch (Exception ex)
                {
                    MsgBox.Error(ex.Message.ToString());
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Text = this.msAppName;
        }
    }
}

Output



By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.