颜色选择器组合框






4.89/5 (14投票s)
使用组合框控件作为颜色选择器。
引言
这是一篇关于如何使用ComboBox
控件作为颜色选择器来显示和选择颜色的简短文章。ComboBox
控件的下拉列表中会显示一个小的颜色条和所有已知颜色的名称,如下所示
背景
要实现此功能,需要在代码中实现ComboBox
控件的DrawItem
事件。ComboBox
控件有一个名为DrawMode
的属性,该属性决定是操作系统还是代码来处理列表中项目的绘制。为了调用DrawItem
事件的实现,必须使用属性窗口将此属性设置为‘OwnerDrawFixed
’。
使用代码
解决方案仅包含一个项目,并且该项目包含一个窗体。在窗体上,我有一个按钮,单击该按钮将在Color
结构中填充所有命名颜色的组合框。我使用选定的颜色来更改窗体上面板的背景颜色。
按钮单击的实现如下所示。我使用反射来获取System.Drawing.Color
结构中所有颜色的集合。然后将颜色名称添加到组合框中。
//
// Button click event handler
//
private void btnLoad_Click(object sender, EventArgs e)
{
ArrayList ColorList = new ArrayList();
Type colorType = typeof(System.Drawing.Color);
PropertyInfo[] propInfoList = colorType.GetProperties(BindingFlags.Static |
BindingFlags.DeclaredOnly | BindingFlags.Public);
foreach (PropertyInfo c in propInfoList)
{
this.cmbboxClr.Items.Add(c.Name);
}
}
在ComboBox
控件的DrawItem
事件中,使用Graphics
对象(可以通过DrawItemEventArgs
的Graphics
属性获得)使用其FillRectangle
方法绘制命名颜色的条。使用DrawString
方法添加颜色的名称。DrawItem
事件将为添加到组合框的每个项目触发。
//
// DrawItem event handler
//
private void cmbboxClr_DrawItem(object sender, DrawItemEventArgs e)
{
Graphics g = e.Graphics;
Rectangle rect = e.Bounds;
if (e.Index >= 0)
{
string n = ((ComboBox)sender).Items[e.Index].ToString();
Font f = new Font("Arial", 9, FontStyle.Regular);
Color c = Color.FromName(n);
Brush b = new SolidBrush(c);
g.DrawString(n, f, Brushes.Black, rect.X, rect.Top);
g.FillRectangle(b, rect.X + 110, rect.Y + 5,
rect.Width -10, rect.Height - 10);
}
}
示例窗体的快照
您可以下载完整的项目并在 Visual Studio 2005 中打开它以获取更多详细信息。