This article briefly describes how Delphi implements items in Listbox to display different colors according to the content. The implementation steps are as follows:
Change the Style property of ListBox1 to lbOwnerDrawVariable
In the OnDrawItem event of the ListBox, change the Canvas property according to the value of the item.
The sample code is as follows:
procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TownerDrawState);begin //The font uses the original default color if Odd(index) then //The color when the index of items is an odd number begin listbox1 .Canvas.Brush.Color:=clwindow; ListBox1.Canvas.TextRect(Rect,rect.Left,Rect.Top,ListBox1.Items[index]); end else //The color when the index of items is an even number begin listbox1.Canvas.Brush.Color:=clinactivecaptiontext; ListBox1 .Canvas.TextRect(Rect,rect.Left,Rect.Top,ListBox1.Items[index]); end; if odSelected in state then //Color when selected begin listbox1.Canvas.Brush.Color:=clhighlight; ListBox1.Canvas.TextRect(Rect,rect.Left,Rect.Top,ListBox1.Items[index]); end;end;