Convert ARGB color value to a KnownColor

G

Guest

Hi,

I've had to solve this in my project and thought the solution would be
useful to others. Basically we first build a hashtable that contains the ARGB
values and associated friendly names, then later we can do a lookup to that.

The example uses the Infragistics UltraColorPicker control but you can use
whatever is relevant.

Regards

=========

//Declare hashtable that holds color value / name pairs
private Hashtable knownColorsHashtable;

//Build hashtable
private static Hashtable BuildKnownColorsHashtable()
{
System.Array knownColors = System.Enum.GetValues(typeof(KnownColor));
Hashtable hashtable = new Hashtable(knownColors.Length);
foreach (object knownColorObject in knownColors)
{
try
{
KnownColor knownColor = (KnownColor)knownColorObject;

Color color = Color.FromKnownColor(knownColor);
int argbValue = color.ToArgb();
string colorName = knownColor.ToString();

if (!color.IsSystemColor)
{
try
{

hashtable.Add(argbValue, colorName);
}
catch (ArgumentException)
{
Debug.WriteLine(argbValue, colorName);
}
}
}
catch (InvalidCastException)
{
}
}
return hashtable;
}

// Do subsequent lookup to get friendly name

public bool GetColorFriendlyName(int argb, out string friendlyName)
{
bool success = true;

if (knownColorsHashtable.ContainsKey(argb))
{
object friendlyNameObject = knownColorsHashtable[argb];
friendlyName = Convert.ToString(friendlyNameObject);
}
else
{
success = false;
friendlyName = "";
}
return success;
}

// in the required method set an Infragistics UltraColorPicker's color to
the friendly name, if the color has a friendly name:

string colorFriendlyName;
if (UserProcess.GetColorFriendlyName(colorArgbValue, out colorFriendlyName))
{
colorPicker.Color = Color.FromName(colorFriendlyName);
}
else
{
colorPicker.Color = Color.FromArgb(colorArgbValue);
}
 
Joined
Apr 11, 2013
Messages
1
Reaction score
0
there is the easiest way (pardon my C++)

Use ColorConverter class!

Drawing::ColorConverter oConvert;
String ^ sBuf = oConvert.ConvertToInvariantString(tBuf);
Object ^ o = oConvert.ConvertFromInvariantString(sBuf);
if (o != nullptr)
{
Drawing::Color tBuf
= *dynamic_cast<System::Drawing::Color^>(o);
tBuf.ToKnownColor(); // <---!!!
}
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top