Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I implement an owner-drawn ListBox?

See Creating an Owner-Drawn Listbox on GotDotNet. It derives from Form and implements the owner drawing by handling the DrawItem event and MeasureItem event.

You can also download a sample that implements an owner drawn listbox by deriving from ListBox and overriding the virtual methods OnDrawItem and OnMeasureItem. Here is a OnDrawItem override that draws colored rectangles in the listbox.

protected override void OnDrawItem( DrawItemEventArgs e )
{
  // undo the selection rect on the old selection
  if ( oldSelectedRect != e.Bounds &&
      oldSelectedIndex > -1 && oldSelectedIndex < Items.Count )
    e.Graphics.DrawRectangle(
      new Pen( (Color) Items[oldSelectedIndex], 2 ), oldSelectedRect );

  // draw the item (here we just fill a rect)
  if ( e.Index > -1 && e.Index < Items.Count)
    e.Graphics.FillRectangle( new SolidBrush( (Color)Items[e.Index] ), e.Bounds );

  // draw selection rect if needed
  if ( SelectedIndex == e.Index )
  {
    e.Graphics.DrawRectangle( new Pen( Color.Black, 2 ), e.Bounds );
    oldSelectedRect = e.Bounds;
    oldSelectedIndex = e.Index;
  }
}

Contributed from George Shepherd's Windows Forms FAQ