Author: Tomas Rutkauskas
Can anyone tell me how to change the default highlight color used in a TListBox? I
need it to be clAqua instead of the standard Navy as the text in the listbox is
made other colors in the OwnerDraw and you can't read some of them with the Navy
selection color.
Answer:
Solve 1:
Check the 'State' parameter in the DrawItem event. It lets you know if the item is
selected. If it is then use a different brush color.
1 2 procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
3 Rect: TRect; State: TOwnerDrawState);
4 begin5 if odSelected in State then6 ListBox1.Canvas.Brush.Color := clAqua;
7 ListBox1.Canvas.FillRect(Rect);
8 ListBox1.Canvas.TextOut(Rect.Left, Rect.Top, ListBox1.Items[Index]);
9 end;
Solve 2:
Set Style := lbOwnerDrawFixed and OnDrawItem := ListBoxDrawItem; . Remove the last
line from the example if you want to have the focus rectangle.
10 11 procedure TListBox.ListBoxDrawItem(Control: TWinControl; Index: Integer; Rect:
12 TRect;
13 State: TOwnerDrawState);
14 begin15 if (odSelected in State) then16 Canvas.Brush.Color := clBlue
17 else18 Canvas.Brush.Color := Color;
19 Canvas.FillRect(Rect);
20 Canvas.Font := Font;
21 SetTextAlign(Canvas.Handle, TA_LEFT or TA_TOP or TA_NOUPDATECP);
22 ExtTextOut(Canvas.Handle, Rect.Left + 2, Rect.Top + 1, ETO_CLIPPED or ETO_OPAQUE,
23 @Rect,PChar(Items[Index]), Length(Items[Index]), nil);
24 if (odSelected in State) then25 DrawFocusRect(Canvas.Handle, Rect);
26 end;