Click here to Skip to main content
15,888,072 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello All,

How can we get the current background color of a control in C# by its Name?
How can we get the current background color of a control in C# by its Name when passing its HexCode?

Any help will be appreciated

Thanks in Advance

Muhammed abdussalam
Posted
Updated 11-Oct-11 22:43pm
v3

C#
Color colorRed = Color.FromArgb(0xFFFF0000);//A color created with this method will return 0 in ToKnownColor()
//if you get a color from Color.FromKnownColor() or if you choose from color list in designer then it will return the name. Example:
colorRed = form.BackColor;
String name = colorRed.ToKnownColor().ToString();
 
Share this answer
 
v2
I do not this is is always possible. Since all the HexCodes need not have a named color.

However you can get the color object corresponding to the HexCodes.

Color color = (Color)ColorConverter.ConvertFromString("#hexValue");

also you can use color translator
http://msdn.microsoft.com/en-us/library/system.drawing.colortranslator.aspx[^]
or
Color.FromArgb[^]
 
Share this answer
 
to get the background color Name of the control we can :
CSS
Color color;
 color = controlId.BackColor; 
 string colorName = color.Name;
 
Share this answer
 
v3
If a colour is created from a hex code, it will not have a name, even if the hex code exactly matches that of a name. So if you want to find that name, you'd have to go through all the possible colours (probably by reflecting on the Color class) and see if there's a match.
 
Share this answer
 
Comments
Salam6331 12-Oct-11 8:16am    
Hello BobJanova

How about the same in WPF?
I think there is no Property like "BackColor"??
use script ntc.js
XML
<script type="text/javascript">
        function onBGColorPicked(sender) {
            var hiddenField = document.getElementById('<%=bgColor.ClientID %>');
            hiddenField.value = sender.getColor();
            // alert(hiddenField.value);

            var n_match = ntc.name(hiddenField.value);
            //alert(n_match);
            n_rgb = n_match[0]; // This is the RGB value of the closest matching color
            n_name = n_match[1]; // This is the text string for the name of the match
            n_exactmatch = n_match[2]; // True if exact color match, False if close-match
            //alert(n_match);
            document.getElementById('<%= hdncolorname.ClientID%>').value = n_match[1];
            //alert(hdncolorname.value);

        }
    </script>
 
Share this answer
 
Comments
CHill60 8-Jul-15 10:03am    
The post is over 3 years old and tagged "C#" NOT javascript...and already properly answered

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