Results 1 to 6 of 6

Thread: Colored ListBox (custom fonts, colors, highlight) Updated! - Now With Class!

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Oct 2008
    Location
    Dominican Republic
    Posts
    733

    Wink Colored ListBox (custom fonts, colors, highlight) Updated! - Now With Class!

    05/August/2009
    I have created a custom class with code, please check the attachments, the class will be there.


    Well, drawing a ListBox isn't as hard as you might think, it's really easy. Take a look at the commented code here:

    Declare a ListBox with events, so we can draw to it later...
    vb.net Code:
    1. Public WithEvents ColoredListBox As New ListBox()

    Create the ListBox...
    vb.net Code:
    1. Public Sub CreateMyListBox()
    2.         'Set the properties you want the listbox to have...
    3.         'ColoredListBox.Items.Clear()
    4.         ColoredListBox.Items.AddRange(New Object() {"Gray", "Green", "Yellow", "Blue", "Pink", "Cyan"})
    5.         ColoredListBox.Location = New System.Drawing.Point(12, 12)
    6.         ColoredListBox.Size = New System.Drawing.Size(260, 224)
    7.         'If you set the draw mode to normal, you will end up with a normal-looking listbox _
    8.         'with the default characteristics, however, if it's OwnerDrawFixed, means that _
    9.         'you can "play with it"
    10.         ColoredListBox.DrawMode = DrawMode.OwnerDrawFixed
    11.         'Here we add the listbox to the parent control, in this case, form1
    12.         Controls.Add(ColoredListBox)
    13.     End Sub

    Now, let's draw our items . Each one of these items have a different color.

    vb.net Code:
    1. Private Sub ColoredListBox_DrawItem _
    2.     (ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) _
    3.     Handles ColoredListBox.DrawItem
    4.         'Draw the background that we are later painting on
    5.         e.DrawBackground()
    6.         'We set the brush default color to white
    7.         Dim myBrush As Brush = Brushes.White
    8.         'This is the brush for changing the item colors..
    9.         Dim itemColor As Brush = Brushes.Black
    10.         'And the custom border color to yellow
    11.         Dim myPen As Pen = Pens.Yellow
    12.         'Of course, another font...
    13.         Dim myFont As New Font("Tahoma", 8)
    14.         'Since the item is always focused and selected, we have to check _
    15.         'for both of these drawing states...
    16.         If e.State = (DrawItemState.Selected Or DrawItemState.Focus) Then
    17.             'If its true then we highlight the item with a black _
    18.             'background and a red border...
    19.             myBrush = Brushes.Black
    20.             myPen = Pens.Red
    21.         End If
    22.         'Change the color of the item depending on it's index
    23.         Select Case e.Index
    24.             Case 0
    25.                 itemColor = Brushes.Gray
    26.             Case 1
    27.                 itemColor = Brushes.Green
    28.             Case 2
    29.                 itemColor = Brushes.Yellow
    30.             Case 3
    31.                 itemColor = Brushes.Blue
    32.             Case 4
    33.                 itemColor = Brushes.Pink
    34.             Case 5
    35.                 itemColor = Brushes.Cyan
    36.         End Select
    37.         'Now we draw :D
    38.         'We draw the background of each item depeding if it's focused/selected or not
    39.         e.Graphics.FillRectangle(myBrush, e.Bounds)
    40.         'Here it draws the border depeding on it's state (the listbox item)
    41.         e.Graphics.DrawRectangle(myPen, e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height)
    42.         'Finally we draw the string...
    43.         e.Graphics.DrawString(ColoredListBox.Items(e.Index).ToString(), _
    44.             myFont, itemColor, e.Bounds.X + 2, e.Bounds.Y, StringFormat.GenericDefault)
    45.         'We added 2 to the X bound so that the string won't be touching the border..
    46.     End Sub

    That's it! You're done! Easy, huh?

    I've attached an example project.

    Thanks to jmcilhinney, NickThissen and Empyreal for baring with me .

    Please give the necessary credits if you are posting or distributing this code in another website, online service, etc. Thanks
    Attached Files Attached Files
    Last edited by tassa; Aug 20th, 2009 at 12:19 AM. Reason: Added updated class with IntelliSense descriptions :D
    "In our profession, precision and perfection are not a dispensable luxury, but a simple necessity."
    Niklaus E. Wirth


    Rate any post that helped you, it's a good way of saying thanks
    Please specify your Visual Studio Version!

    Why rating is useful

    My Code Bank Submissions: How to determine Windows Version| Working With Mouse Events | Blocking Input Using API | Get host's IP | Minimize to system tray "animated" | Colored ListBox (custom fonts, colors, highlight) Updated -New Class! | [VS 2008] Strong encryption and hashing class - Updated! 31/August/2009 | Create a shortcut using IWshRuntimeLibrary

  2. #2
    PowerPoster JuggaloBrotha's Avatar
    Join Date
    Sep 2005
    Location
    Lansing, MI; USA
    Posts
    4,286

    Re: Colored ListBox (custom fonts, colors, highlight)

    This is extremely similar to my ColorComboBox, except I have it hold a separate list for the colors to be displayed and instead of coloring the text itself, draws a box with the color in it.

    I'm glad I'm not the only one who had a use for something like this.
    Currently using VS 2015 Enterprise on Win10 Enterprise x64.

    CodeBank: All ThreadsColors ComboBoxFading & Gradient FormMoveItemListBox/MoveItemListViewMultilineListBoxMenuButtonToolStripCheckBoxStart with Windows

  3. #3

    Thread Starter
    Fanatic Member
    Join Date
    Oct 2008
    Location
    Dominican Republic
    Posts
    733

    Re: Colored ListBox (custom fonts, colors, highlight)

    I see, it's a very cool class that you came up with. It hadn't been my intention to post something similar, I just thought that someone would like to have a colored listbox, with a different highlight and the text being, ummm, "unique". I used the names of the colors as an example string since I didn't know what to write. Lol...
    "In our profession, precision and perfection are not a dispensable luxury, but a simple necessity."
    Niklaus E. Wirth


    Rate any post that helped you, it's a good way of saying thanks
    Please specify your Visual Studio Version!

    Why rating is useful

    My Code Bank Submissions: How to determine Windows Version| Working With Mouse Events | Blocking Input Using API | Get host's IP | Minimize to system tray "animated" | Colored ListBox (custom fonts, colors, highlight) Updated -New Class! | [VS 2008] Strong encryption and hashing class - Updated! 31/August/2009 | Create a shortcut using IWshRuntimeLibrary

  4. #4
    PowerPoster JuggaloBrotha's Avatar
    Join Date
    Sep 2005
    Location
    Lansing, MI; USA
    Posts
    4,286

    Re: Colored ListBox (custom fonts, colors, highlight)

    Just to let you know, before you zip your project and upload it to the site here, go in and delete the Bin and Obj folders because they contain compiled code which isn't allowed on this forum.
    Currently using VS 2015 Enterprise on Win10 Enterprise x64.

    CodeBank: All ThreadsColors ComboBoxFading & Gradient FormMoveItemListBox/MoveItemListViewMultilineListBoxMenuButtonToolStripCheckBoxStart with Windows

  5. #5
    PowerPoster JuggaloBrotha's Avatar
    Join Date
    Sep 2005
    Location
    Lansing, MI; USA
    Posts
    4,286

    Re: Colored ListBox (custom fonts, colors, highlight)

    This is another nudge for ya:
    Code:
    Option Explicit On
    Option Strict On
    Option Infer Off
    
    Imports System.ComponentModel
    
    Public Class ColoredListBox
        Inherits System.Windows.Forms.ListBox
    
        Public Sub New()
            MyBase.DrawMode = Windows.Forms.DrawMode.OwnerDrawVariable
            Me.Items.Clear()
        End Sub
    
        <Browsable(False), EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), _
        DefaultValue(Windows.Forms.DrawMode.OwnerDrawVariable)> _
        Public Shadows ReadOnly Property DrawMode() As System.Windows.Forms.DrawMode
            Get
                Return System.Windows.Forms.DrawMode.OwnerDrawVariable
            End Get
        End Property
    
        Protected Overrides Sub OnFontChanged(ByVal e As System.EventArgs)
            Select Case True
                Case Me.Font.SizeInPoints > 12.0F : Me.Font = New Font(Me.Font.FontFamily, 12.0F, Me.Font.Style)
                Case Me.Font.SizeInPoints < 8.0F : Me.Font = New Font(Me.Font.FontFamily, 8.0F, Me.Font.Style)
            End Select
        End Sub
    
        Protected Overrides Sub onDrawItem(ByVal e As System.Windows.Forms.DrawItemEventArgs)
            e.DrawBackground()
            If e.Index >= 0I AndAlso DesignMode = False Then
                Dim myBrush As Brush = Brushes.White
                Dim myPen As Pen = Pens.Blue
                If e.State = (DrawItemState.Selected Or DrawItemState.Focus) Then
                    myBrush = Brushes.Black
                    myPen = Pens.Red
                End If
                e.Graphics.FillRectangle(myBrush, e.Bounds)
                e.Graphics.DrawRectangle(myPen, e.Bounds.X, e.Bounds.Y, e.Bounds.Width - 1I, e.Bounds.Height)
                e.Graphics.DrawString(CType(Me.Items(e.Index), ItemDate).ToString, Me.Font, New SolidBrush(CType(Me.Items(e.Index), ItemData).ItemColor), e.Bounds.X + 2, e.Bounds.Y, StringFormat.GenericDefault)
            End If
        End Sub
    End Class
    
    Public Class ItemData
    
        Private m_Item As Object
        Private m_Color As Color
    
        Public Sub New(ByVal Item As Object, ByVal ItemColor As Color)
            m_Item = Item
            m_Color = ItemColor
        End Sub
    
        Public Property Item() As Object
            Get
                Return m_Item
            End Get
            Set(ByVal value As Object)
                m_Item = value
            End Set
        End Property
    
        Public Property ItemColor() As Color
            Get
                Return m_Color
            End Get
            Set(ByVal value As Color)
                m_Color = value
            End Set
        End Property
    
        Public Overrides Function ToString() As String
            Return m_Item.ToString()
        End Function
    End Class
    Last edited by JuggaloBrotha; Aug 1st, 2009 at 08:24 AM.
    Currently using VS 2015 Enterprise on Win10 Enterprise x64.

    CodeBank: All ThreadsColors ComboBoxFading & Gradient FormMoveItemListBox/MoveItemListViewMultilineListBoxMenuButtonToolStripCheckBoxStart with Windows

  6. #6
    Frenzied Member
    Join Date
    Jun 2007
    Location
    India
    Posts
    1,158

    Re: Colored ListBox (custom fonts, colors, highlight) Updated! - Now With Class!

    with reference to code in post #1

    the listbox is not able to display the selected back color if it looses the focus

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width