Archive for January, 2007|Monthly archive page

Change ListBox background color

The screenshot below is from an interesting software I wrote for my college final project. It is an assembly and microinstruction emulator that gives you the chance to debug and monitor all the registers, controllers, buses and memory values. I’ll try to talk more about that project in future posts.

On the form we have a RichTextBox on the left, where we can write macroinstructions (i.e., assembly) and on the top left we have a ListBox that contains the default microinstruction program.  So as we debug the instructions we have to keep track of which command line is being executed, both on the macro and micro-program.

To give it a Visual Studio feeling I decided to highlight the current command line.

The RichTextBox already has a built-in SelectionBackColor property, so the only thing I had to do was to select the current command and set the property to yellow.

On the other hand, the ListBox doesn’t have any built-in property like that. But I found a pretty easy way to do it.

The ListBox control exposes a DrawItem event that we can use to override the default drawing for each item.
First we need to set the DrawMode property of the ListBox to DrawMode.OwnerDrawFixed. This can be done on the form’s constructor, right after the InitializeComponent method is called.
Then, on the DrawItem event handler we need to write the following code to draw the ListBox item.  

private void lbMIC_DrawItem(object sender, DrawItemEventArgs e)
    // if we call the DrawBackground method, 
    // it will use the default gray color to paint the background
    Brush backGroundBrush;

    // Determines if the current item is the selected one
    if ((e.State & DrawItemState.Selected) > 0)
        //It is the selected one, so we use yellow
        backGroundBrush = Brushes.Yellow;                
        //It isn't the selected one, 
        //so we use the default white color
        backGroundBrush = Brushes.White;                

    // Draw the background as a rectangle using 
    //the color defined above
    e.Graphics.FillRectangle(backGroundBrush, e.Bounds);

    // Draw the text of the item
    // Here you can also change the text fore color
    if (e.Index > -1)
        	e.Font, Brushes.Black, e.Bounds);


With this in mind, we could easily create an inherited ListBox control with a built-in SelectedItemBackColor property.

Hope it helps.