65.9K
CodeProject 正在变化。 阅读更多。
Home

颜色选择器组合框

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.89/5 (14投票s)

2009年3月20日

CPOL

2分钟阅读

viewsIcon

123652

downloadIcon

7508

使用组合框控件作为颜色选择器。

引言

这是一篇关于如何使用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对象(可以通过DrawItemEventArgsGraphics属性获得)使用其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 中打开它以获取更多详细信息。

© . All rights reserved.