// 看看这样行不行
[STAThread]
public static void Main(string[] args)
{
var argbColor = Color.FromArgb(255, 255, 0, 0);
var colorName = FindColorName(argbColor);
if (string.IsNullOrEmpty(colorName))
Console.WriteLine("未找到");
else
Console.WriteLine(colorName);
Console.ReadKey();
}
private static string FindColorName(Color argbColor)
{
var propertyInfos = typeof (Color).GetProperties(BindingFlags.Public | BindingFlags.Static);
foreach (var propertyInfo in propertyInfos)
{
if (!propertyInfo.CanRead)
continue;
var value = propertyInfo.GetValue(null, null);
if (!(value is Color))
continue;
if (((Color) value).ToArgb() == argbColor.ToArgb())
return propertyInfo.Name;
}
return null;
}
追问好像可以,但是我是新手,你这个程序其实我都不太清楚该放在哪里运行,是winform还是控制台
追答放在winfrom或是控制台都可以。我的演示代码是使用控制台程序。把FindColorName这个函数放在需要使用中类中即可。还有记得引用程序集System.Drawing.dll .
原理和你说下,因为Color中定义了很多常用颜色名称,比如Color.Red。这段代码就是通过反射取出所有这些定义的颜色名称,然后与需要查询的颜色进行比较,如果一致就返回颜色名称。