一、用VS新建一个C# WinForm程序
以下是本例程会使用到的命名空间:
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;
二、添加初始化方法
public void ColorCmb_Init(ComboBox cmb)
{
//设置手动绘制
cmb.DrawMode = DrawMode.OwnerDrawFixed;
cmb.DropDownStyle = ComboBoxStyle.DropDownList;
//
cmb.DrawItem += cmb_DrawItem;
//将Color转化为属性信息列表,以便于遍历信息将对应名称添加到ComboBox选项中
PropertyInfo[] proInfoList = typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public);
foreach (PropertyInfo item in proInfoList)
{
cmb.Items.Add(item.Name);
}
//初始化选择颜色
cmb.Text = “White”;
}
三、添加绘制委托方法
private void cmb_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
e.DrawFocusRectangle();
if (e.Index < 0)
return;
ComboBox cmb = (ComboBox)sender;
string colorName = cmb.Items[e.Index].ToString();
Color color = Color.FromName(colorName);
//画笔
SolidBrush brush = new SolidBrush(color);
Graphics g = e.Graphics;
//获取表示所绘制项的边界矩形
Rectangle rect = e.Bounds;
//结构放大指定量
rect.Inflate(-2, -2);
//new Size(40, rect.Height), 40: 下拉框添加项的宽度;rect.Height: 下拉框添加项的高度
Rectangle rectColor = new Rectangle(rect.Location, new Size(40, rect.Height));
//绘制边框
g.DrawRectangle(new Pen(e.ForeColor), rectColor);
//填充颜色
g.FillRectangle(brush, rectColor);
//绘制文本ColorToString(color)
g.DrawString(color.Name, new Font("宋体", 9), new SolidBrush(e.ForeColor), (rect.X + 50), rect.Y);
}
四、在From1_Load中添加初始化方法
private void Form1_Load(object sender, EventArgs e)
{
ColorCmb_Init(comboBox1);
}