I'm curious to know if there's a good way to see if an object is a System.Drawing.Color before I try casting it to one. Right now it seems the only way I can do that is to put it in a Try/Catch block and if it hit's the catch part then I know the object isn't a color. Here's my code so far:
I really don't like this because there's a slight flicker while it fires up the Exception handling and I would really rather use an If Else End If for this than a Try/Catch.
VB.NET:
Protected Overrides Sub onDrawItem(ByVal e As System.Windows.Forms.DrawItemEventArgs)
e.DrawBackground()
e.DrawFocusRectangle()
If e.Index > -1I AndAlso Me.Items.Count > 0I Then
' Get the Color object from the Items list
Dim br As Brush = If((e.State And DrawItemState.Selected) = DrawItemState.Selected, Brushes.White, Brushes.Black)
Try
Dim aColor As Color = CType(Me.Items(e.Index), Color)
' get a square using the bounds height
Dim rect As Rectangle = New Rectangle(5I, e.Bounds.Top + 2I, e.Bounds.Height - 3I, e.Bounds.Height - 5I)
' draw a rectangle and fill it
e.Graphics.DrawRectangle(New Pen(aColor), rect)
e.Graphics.FillRectangle(New SolidBrush(aColor), rect)
' draw a border
rect.Inflate(1I, 1I)
e.Graphics.DrawRectangle(Pens.Black, rect)
' draw the Color name
e.Graphics.DrawString(aColor.Name, Me.Font, br, e.Bounds.Height + 5I, ((e.Bounds.Height - Me.Font.Height) \ 2I) + e.Bounds.Top)
Catch
'Not a color, skip the drawing of a square
e.Graphics.DrawString(Me.Items(e.Index).ToString, Me.Font, br, e.Bounds.Height + 5I, ((e.Bounds.Height - Me.Font.Height) \ 2I) + e.Bounds.Top)
End Try
End If
End Sub