颜色列表框






4.88/5 (9投票s)
带有颜色名称和预览的列表框
 
 
引言
这是一个可以查看默认或自定义颜色名称和预览的列表框。
Using the Code
这些项目是在 DrawItem 事件中手动绘制的。它仅在 listbox 的 DrawMode 属性设置为 OwnerDrawFixed 或 OwnerDrawVariable 时运行。
这是我的 DrawItem 代码
Private Sub ColoredComboBox_DrawItem(ByVal sender As Object, _
	ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles Me.DrawItem
    Try
        If e.Index = -1 Then Exit Sub
        Dim mycolor As String = Strings(e.Index)
        Dim brush1 As Brush = New SolidBrush(GetColor(e.Index))
        Dim rect As Rectangle = e.Bounds
        e.Graphics.FillRectangle(New SolidBrush(sender.backcolor), rect)
        Dim highlightcolor As Color = SystemColors.Highlight
        If (e.State = DrawItemState.Focus) _
        	Or (e.State = DrawItemState.Selected) _
        	Or (e.State = DrawItemState.Selected + DrawItemState.Focus) Then
            e.Graphics.FillRectangle(New SolidBrush(highlightcolor), e.Bounds)
        Else
            e.Graphics.FillRectangle(New SolidBrush(sender.BackColor), e.Bounds)
        End If
        rect.Width = WidthOfColorBar
        rect.Height -= 4
        rect.X += 2
        rect.Y += 2
        e.Graphics.FillRectangle(brush1, rect)
        e.Graphics.DrawRectangle(Pens.Black, rect)
        e.Graphics.DrawString(mycolor, sender.font, _
        	New SolidBrush(sender.forecolor), WidthOfColorBar + 5, rect.Y - 2)
    Catch ex As Exception
    
    End Try
End Sub 
首先,它设置变量。
然后它清除项目旧的状态
e.Graphics.FillRectangle(New SolidBrush(sender.backcolor), rect)  
然后它检查此项目是否被焦点选中或两者都有,并用高亮颜色填充它。
然后绘制颜色预览和项目值。
这个类有两个数组
- Colors:它包含项目的颜色。
- Strings:它包含项目值。
这个类有两个属性
- SelectedColor:它返回选中项目的颜色。该颜色来自 Colors(- Me.SelectedIndex)。它是只读的。
- ColorBarWidth:它设置或获取颜色条预览的宽度。
它还包含两个子例程,用于将项目添加到 listbox 中
- 
Public Sub AddItem(ByVal Item As String, ByVal Color As Color) 它将 " Item"string与 "Color" 预览添加到listbox中。
- 
Public Sub AddKnownColors() 它将所有已知颜色及其默认名称添加到 listbox中。
这是 AddKnownColors() 的代码
Dim colorTable As Color = New Color
Dim t As Type = GetType(Color)
Dim pis() As System.Reflection.PropertyInfo = t.GetProperties
For Each pi As System.Reflection.PropertyInfo In pis
    If (pi.PropertyType Is GetType(Color)) Then
        Dim color As Color = CType(pi.GetValue(colorTable, Nothing), Color)
        AddItem(color.Name, color)
    End If
Next
关注点
请记住,如果 listbox 的 DrawMode 属性为 Normal,则 DrawItem 事件将不会运行!
历史
- 12-01-2009
- 一个可以查看默认或自定义颜色名称和预览的列表框(第一个版本)


