bdn.borland.com

Article #27718: How can I make the background color different for alternating lines of text in a TListBox in Delphi?

QUESTION:


How can I make the background color different for alternating lines of text in a TListBox in Delphi?


ANSWER:


Here is one way of accomplishing this. After dropping a TListBox on your form, you must change the Style property of the TListBox to lbOwnerDrawFixed. If you fail to change the Style property, the OnDrawItem event will never be called. Put the following code in the OnDrawItem event of your TListBox:

procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
  Rect: TRect; State: TOwnerDrawState);
var
    myColor: TColor;
    myBrush: TBrush;      
begin
  myBrush := TBrush.Create;  
  with (Control as TListBox).Canvas do // draw on control canvas, not on the form
  begin
    if not Odd(Index) then
      myColor := clSilver
    else
      myColor := clYellow;

    myBrush.Style := bsSolid; 
    myBrush.Color := myColor; 

    Windows.FillRect(handle, Rect, myBrush.Handle); 

    Brush.Style := bsClear;  
    // display the text 
    TextOut(Rect.Left, Rect.Top, (Control as TListBox).Items[Index]);  
    MyBrush.Free;
  end;
end;

Last Modified: 19-SEP-01