你好,无论如何
例如,如果我使用Visual Studio在Winform中设置Panel的BackColor,我可以从3个列表中选择颜色:
自定义,Web,系统
是否有可能只在我的C#代码应用程序中检索Web颜色?它们是KnownColor的一部分,但到目前为止我只能找到如何从列表中删除系统控制.
我想使用网页颜色,因为它们以一种很好的方式排序,我想将它们插入一个自我实现的组合框中.
谢谢
var webColors =
Enum.GetValues(typeof(KnownColor))
.Cast<KnownColor>()
.Where (k => k >= KnownColor.Transparent && k < KnownColor.ButtonFace) //Exclude system colors
.Select(k => Color.FromKnownColor(k));
Run Code Online (Sandbox Code Playgroud)
编辑:
要订购颜色附加:
.OrderBy(c => c.GetHue())
.ThenBy(c => c.GetSaturation())
.ThenBy(c => c.GetBrightness());
Run Code Online (Sandbox Code Playgroud)
Colorstruct包含所有Web颜色作为常量(系统颜色在SystemColors类中定义为常量)
要获得这些颜色的列表,请执行以下操作:
var webColors = GetConstants(typeof(Color));
var sysColors = GetConstants(typeof(SystemColors));
Run Code Online (Sandbox Code Playgroud)
具有GetConstants定义如下:
static List<Color> GetConstants(Type enumType)
{
MethodAttributes attributes = MethodAttributes.Static | MethodAttributes.Public;
PropertyInfo[] properties = enumType.GetProperties();
List<Color> list = new List<Color>();
for (int i = 0; i < properties.Length; i++)
{
PropertyInfo info = properties[i];
if (info.PropertyType == typeof(Color))
{
MethodInfo getMethod = info.GetGetMethod();
if ((getMethod != null) && ((getMethod.Attributes & attributes) == attributes))
{
object[] index = null;
list.Add((Color)info.GetValue(null, index));
}
}
}
return list;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
要获得与VS完全相同的颜色排序:
var webColors = GetConstants(typeof(Color));
var sysColors = GetConstants(typeof(SystemColors));
webColors.Sort(new StandardColorComparer());
sysColors.Sort(new SystemColorComparer());
Run Code Online (Sandbox Code Playgroud)
用StandardColorComparer和SystemColorComparer定义如下:
class StandardColorComparer : IComparer<Color>
{
// Methods
public int Compare(Color color, Color color2)
{
if (color.A < color2.A)
{
return -1;
}
if (color.A > color2.A)
{
return 1;
}
if (color.GetHue() < color2.GetHue())
{
return -1;
}
if (color.GetHue() > color2.GetHue())
{
return 1;
}
if (color.GetSaturation() < color2.GetSaturation())
{
return -1;
}
if (color.GetSaturation() > color2.GetSaturation())
{
return 1;
}
if (color.GetBrightness() < color2.GetBrightness())
{
return -1;
}
if (color.GetBrightness() > color2.GetBrightness())
{
return 1;
}
return 0;
}
}
class SystemColorComparer : IComparer<Color>
{
// Methods
public int Compare(Color color, Color color2)
{
return string.Compare(color.Name, color2.Name, false, CultureInfo.InvariantCulture);
}
}
Run Code Online (Sandbox Code Playgroud)
NB:
此代码来自System.Drawing.Design.ColorEditor反射器.