ColorComboBox






4.31/5 (15投票s)
2003年10月5日
2分钟阅读

143861

1937
使用组合框选择颜色。
引言
ColorComboBox 类是作为我正在进行的另一个项目的一部分而组合在一起的。 想法显然是您可以更改应用程序中某些东西的颜色。 不幸的是,在大多数 Windows 应用程序中执行此操作的方法是弹出标准颜色对话框并选择您想要的颜色。 我确信我不是唯一一个认为这很俗气的人,并且认为应该有一种方法可以做到这一点,而不会分散您对应用程序的注意力。 因此,我提出了这个类,我觉得这是一种更简单、更优雅的实现方式。


从图像中可以看出,有两种使用该类的方法:一种在下拉显示中不显示文本名称,另一种显示。 我必须承认,当我第一次编写这个类时,我认为它看起来没有文本会更好。 虽然,在并排看到这两个之后,我现在更倾向于包含下拉列表中文本的实现。
实现
这里没有什么真正复杂的事情,因为该类只是标准 ComboBox 的扩展,但我将为新手介绍实现的主要几点。 主要的更改是告诉 ComboBox,第一,我希望接管控件的绘图,第二,覆盖绘图函数,以便我可以按照我自己的方式实现绘图。 这是通过
this.DrawMode = DrawMode.OwnerDrawFixed;
this.DrawItem += new DrawItemEventHandler( OnDrawItem );
它包含在类的构造函数中。 OnDrawItem 函数的实现是
Graphics grfx = e.Graphics;
Color brushColor = GetColorFromString( ( string )this.Items[ e.Index ] );
SolidBrush brush = new SolidBrush( brushColor );
grfx.FillRectangle( brush, e.Bounds );
if( bHideText == false )
{
    if( brushColor == Color.Black || brushColor == Color.MidnightBlue
        || brushColor == Color.DarkBlue || brushColor == Color.Indigo
        || brushColor == Color.MediumBlue || brushColor == Color.Maroon
        || brushColor == Color.Navy || brushColor == Color.Purple )
    {
        grfx.DrawString( ( string )this.Items[ e.Index ],
              e.Font, whiteBrush, e.Bounds );
    }
    else
    {
        grfx.DrawString( ( string )this.Items[ e.Index ],
              e.Font, blackBrush, e.Bounds );
    }
    this.SelectionStart = 0;
    this.SelectionLength = 0;
}
else
{
    grfx.DrawString( ( string )this.Items[ e.Index ], e.Font,
        new SolidBrush( GetColorFromString(
          ( string )this.Items[ e.Index ] ) )
          , e.Bounds );
}
每次代码试图在 ComboBox 的下拉 ListBox 部分绘制一个单元项时都会调用该函数。 调用该函数时,代码会获取 ListBox 项中包含的 Color。 由于颜色数据以通常的方式存储在 ComboBox 的 ListBox 部分中,作为字符串,并且如果需要,代码会通过将项目的颜色更改为与背景颜色相同的颜色来隐藏字符串。
一旦它有了 Color,它就会将背景颜色设置为该颜色,然后以背景颜色绘制 ListBox 项的矩形。 完成后,代码只需以可见或不可见的方式将颜色的字符串名称绘制到 ListBox 项中,具体取决于 bool 值 bHideText。
历史
- 2003 年 10 月 5 日:- 初始发布。
- 2004 年 8 月 9 日:- 修复了由覆盖 OnSelectionChangeCommitted引起的绘图错误。
