Introduction
This is a list box that can view default or own color names and previews.
Using the Code
These items are manually draw in DrawItem
event. It only runs if DrawMode
property of listbox
is set to OwnerDrawFixed
or OwnerDrawVariable
.
Here is my DrawItem
code:
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
First, it sets variables.
Then it clears the old state of item:
e.Graphics.FillRectangle(New SolidBrush(sender.backcolor), rect)
It then checks if this item is focused or selected or both, and fills it with the highlight Color.
Then Draw Color Preview and item value.
This class has two arrays:
Colors
: It has colors of items. Strings
: It has item values.
This class has two properties:
SelectedColor
: It returns the color of the selected item. That color is from Colors(Me.SelectedIndex
). It is ReadOnly. ColorBarWidth
: It sets or gets the Width of Color Bar Previews.
Also it has two subroutines for adding items into the listbox
:
-
Public Sub AddItem(ByVal Item As String, ByVal Color As Color)
It adds "Item
" string
with "Color
" preview into the listbox
.
-
Public Sub AddKnownColors()
It adds all Known Colors with their default names into the listbox
.
Here is the code for 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
Points of Interest
Remember, if DrawMode
property of a listbox
is Normal
, DrawItem
Event will not run!
History
- 12-01-2009
- A
listbox
that can view default or own color names and previews (first version)