Public Class udcColorOnlyComboBox : Inherits ComboBox
Private Colors() As String = New String() {"", "Red", "Green", "Blue", "Orange"}
Public Sub New()
InitializeComboBox()
End Sub
' This method initializes the owner-drawn combo box.
' The drop-down width is set much wider than the size of the combo box
' to accomodate the large items in the list. The drop-down style is set to
' ComboBox.DropDown, which requires the user to click on the arrow to
' see the list.
Private Sub InitializeComboBox()
Me.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable
Me.Location = New System.Drawing.Point(10, 20)
Me.Name = "ComboBox1"
Me.Size = New System.Drawing.Size(100, 120)
Me.DropDownWidth = 250
Me.TabIndex = 0
Me.DropDownStyle = ComboBoxStyle.DropDown
Me.DataSource = Colors
End Sub
' If you set the Draw property to DrawMode.OwnerDrawVariable,
' you must handle the MeasureItem event. This event handler
' will set the height and width of each item before it is drawn.
Private Sub ComboBox1_MeasureItem(ByVal sender As Object, _
ByVal e As System.Windows.Forms.MeasureItemEventArgs) _
Handles Me.MeasureItem
e.ItemHeight = 15
e.ItemWidth = Me.Width
End Sub
' You must handle the DrawItem event for owner-drawn combo boxes.
' This event handler changes the color, size and font of an
' item based on its position in the array.
Private Sub ComboBox1_DrawItem(ByVal sender As Object, _
ByVal e As System.Windows.Forms.DrawItemEventArgs) _
Handles Me.DrawItem
'Dim size As Single
Dim myFont As System.Drawing.Font = New Font(FontFamily.GenericSerif, 8.25, FontStyle.Regular)
Dim backColor As System.Drawing.Color = ColorTranslator.FromHtml(Colors(e.Index))
' Draw the background of the item.
e.DrawBackground()
' Create a square filled with the animals color. Vary the size
' of the rectangle based on the length of the animals name.
Dim rectangle As Rectangle = New Rectangle(2, e.Bounds.Top + 2, _
e.Bounds.Height, e.Bounds.Height - 4)
e.Graphics.FillRectangle(New SolidBrush(backColor), rectangle)
' Draw each string in the array, using a different size, color,
' and font for each item.
e.Graphics.DrawString(Colors(e.Index), myFont, System.Drawing.Brushes.Black, _
New RectangleF(e.Bounds.X + rectangle.Width, e.Bounds.Y, _
e.Bounds.Width, e.Bounds.Height))
' Draw the focus rectangle if the mouse hovers over an item.
e.DrawFocusRectangle()
End Sub
End Class