How to change ListBox selection background color?

Qosmo picture Qosmo · Sep 8, 2010 · Viewed 49.2k times · Source

It seems to use default color from Windows settings which is blue by default. Let's say I want to change it to red permanently. I'm using Winforms.

Thanks in advance.

Answer

RRUZ picture RRUZ · Sep 8, 2010

You must override the Drawitem event and set the DrawMode property to DrawMode.OwnerDrawFixed

check this sample

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    if (e.Index<0) return;
    //if the item state is selected them 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.Yellow);//Choose the color

    // Draw the background of the ListBox control for each item.
    e.DrawBackground();
    // Draw the current item text
    e.Graphics.DrawString(listBox1.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();
}

alt text