tags:

views:

39

answers:

2

So I have this code to change the background selection colour of a listbox item to red in the default Winforms.

if (e.Index < 0) return;
            // if the item state is selected then change the back color 
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                e = new DrawItemEventArgs(e.Graphics,
                                          e.Font,
                                          e.Bounds,
                                          e.Index,
                                          e.State ^ DrawItemState.Selected,
                                          e.ForeColor,
                                          Color.Red); // Choose the color

            // Draw the background of the ListBox control for each item.
            e.DrawBackground();
            // Draw the current item text
            e.Graphics.DrawString(studentsListBox.Items[e.Index].ToString(), e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
            // If the ListBox has focus, draw a focus rectangle around the selected item.
            e.DrawFocusRectangle();

This works fine but I also want to change the font color for the selected item. How do I do it?

A: 

Can't you just supply a color other than e.ForeColor?

Jim Mischel
+1  A: 
if (e.Index < 0)
    return;

Brush foreBrush = Brushes.Black; // non-selected text color
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
    foreBrush = Brushes.White; // selected text color
    e = new DrawItemEventArgs(e.Graphics,
                              e.Font,
                              e.Bounds,
                              e.Index,
                              e.State ^ DrawItemState.Selected,
                              e.ForeColor,
                              Color.Red); // Choose the color 
}

// Draw the background of the ListBox control for each item. 
e.DrawBackground();
// Draw the current item text
e.Graphics.DrawString((sender as ListBox).Items[e.Index].ToString(), e.Font, foreBrush, e.Bounds, StringFormat.GenericDefault);
// If the ListBox has focus, draw a focus rectangle around the selected item. 
e.DrawFocusRectangle(); 
Tergiver
The brush needs to be disposed and you still have to draw the background if index < 0.
Hans Passant
@Hans: Disposing one of the System.Drawing.Brushes (readonly static objects) is a very bad idea. You really only have to draw the background if it differs from the control's BackColor (i.e. WNDCLASS.hbrBackground) since WM_ERASEBKGND will take care of it.
Tergiver
Yes, good point.
Hans Passant
Works as intended, thanks!
Queops