How do I customize the colors displayed on a ListBox (or other controls)?
The TLIstbox, TComboBox, TListView, TListBox, TMenuItem, and TOutline VCL controls all expose an event named OnDrawItem that is used for this purpose. An event handler associated with this event will intercept any item drawing that takes place in the control. Using this event handler, you become responsible for writing the code that draws items in the control. Note: OnDrawItem occurs only for owner-draw list boxes.
The data passed to your event handler will differ among the different controls, but some of the common ones are:
- A pointer to the control
- An integer indicating the index of the item being drawn
- A TRect representing the area the item occupies in the control's canvas
- An indicator of the state the item is in, i.e. checked, selected, focused, etc. (this may affect the way you choose to draw the item)
Below is a simple example of using this event. This example alternates the drawing colors of items in a TListBox.
void __fastcall TForm1::ListBox1DrawItem(TWinControl *Control, int Index,
TRect &Rect, TOwnerDrawState State)
TListBox *pListbox = dynamic_cast<TListBox*>(Control);
TCanvas *pCanvas = pListbox->Canvas;
if (State.Contains(odSelected)) // if the item is selected draw with selection colors
pCanvas->Brush->Color = clHighlight;
pCanvas->Font->Color = clHighlightText;
else if(Index%2) // every other row gets colored differently
// other rows revert to default coloring for the control
pCanvas->Brush->Color = clAqua;
pCanvas->Font->Color = clMaroon;
// redraws the background color;
// draws the text inside the item rectangle
pCanvas->TextRect(Rect, Rect.Left,Rect.Top, pListbox->Items->Strings[Index]);