Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
' Private Sub FillListBoxWithColors()
' Make the listbox owner-draw.
ListBox1.DrawMode = DrawMode.OwnerDrawFixed
ListBox1.ItemHeight = 24
' Avoid flickering.
ListBox1.BeginUpdate()
ListBox1.Items.Clear()
' Create a list of all the properties in the Color class.
Dim pi As Reflection.PropertyInfo
For Each pi In GetType(Color).GetProperties(Reflection.BindingFlags.Static Or Reflection.BindingFlags.Public)
' Add the name of the property (that is, the color) to the ListBox.
ListBox1.Items.Add(pi.Name)
Next
' Now display the result.
ListBox1.EndUpdate()
End Sub
' this event handler is called for each element about to be drawn
Private Sub ListBox1_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles ListBox1.DrawItem
' Get the rectangle to be drawn.
Dim rect As Rectangle = e.Bounds
' If this is the selected item, draw the background.
If CBool(e.State And DrawItemState.Selected) Then
' Fill the rectable with the highlight system color.
e.Graphics.FillRectangle(SystemBrushes.Highlight, rect)
Else
' else, fill the rectangle with the Window system color.
e.Graphics.FillRectangle(SystemBrushes.Window, rect)
End If
' Get the color of the item to be drawn.
Dim colorName As String = CStr(ListBox1.Items(e.Index))
' Build a brush of that color
Dim b As New SolidBrush(Color.FromName(colorName))
' Shrink the rectangle by some pixels.
rect.Inflate(-16, -2)
' Draw the rectangle interior.
e.Graphics.FillRectangle(b, rect)
' Draw the rectable outline.
e.Graphics.DrawRectangle(Pens.Black, rect)
' select an appropriate color for the brush
Dim b2 As Brush
If CInt(b.Color.R) + CInt(b.Color.G) + CInt(b.Color.B) > 128 * 3 Then
b2 = Brushes.Black
Else
b2 = Brushes.White
End If
' draw the name of the color using the default font.
e.Graphics.DrawString(colorName, e.Font, b2, rect.X + 4, rect.Y + 2)
' destroy the custom brush
' (don't dispose b2, because it is a system brush)
b.Dispose()
End Sub
' this is necessary, otherwise items don't redraw correctly when the form resizes.
Private Sub ListBox1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.Resize
ListBox1.Refresh()
End Sub
' display the RGB value of the color under the mouse cursor
Private Sub ListBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseMove
' don't do anything if we aren't showing colors
If ListBox1.DrawMode = DrawMode.Normal Then Exit Sub
' get the index of the element under the mouse cursor.
Dim index As Integer = ListBox1.IndexFromPoint(e.X, e.Y)
' exit if no valid entry.
If index = ListBox.NoMatches Then Exit Sub
' get the corresponding color.
Dim c As Color = Color.FromName(CStr(ListBox1.Items(index)))
End Sub