這篇文章主要介紹了c#構造ColorComboBox的代碼分享,大家參考使用吧
代碼如下:
class ColorComboBox : ComboBox
{
/// <summary>
/// 當前選中色
/// </summary>
public Color SelectedColor
{
get { return Color.FromName(this.Text); }
}
/// <summary>
/// 構造函數,構造顏色下拉列表
/// </summary>
public ColorComboBox()
{
this.DrawMode = DrawMode.OwnerDrawFixed;
this.DropDownStyle = ComboBoxStyle.DropDownList;
this.ItemHeight = 25;
PropertyInfo[] propInfoList = typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public);
foreach (PropertyInfo c in propInfoList)
{
this.Items.Add(c.Name);
}
this.Text = "Black"; //設置默認色
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
Rectangle rect = e.Bounds;
if (e.Index >= 0)
{
string colorName = this.Items[e.Index].ToString();
Color c = Color.FromName(colorName);
using (Brush b = new SolidBrush(c)) //預留下拉項間距
{
e.Graphics.FillRectangle(b, rect.X, rect.Y + 2, rect.Width, rect.Height - 4);
}
}
}