Mega Code Archive

 
Categories / Delphi / VCL
 

How to display a tlistbox with alternating colors

unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; ListBox1: TListBox; procedure Button1Click(Sender: TObject); procedure ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin ListBox1.AddItem('Test',nil); ListBox1.AddItem('Test II',nil); ListBox1.AddItem('Test III',nil); end; procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var ListColor: TColor; ListBrush: TBrush; begin { TForm1.ListBox1DrawItem } // create a brush to paint the item's background ListBrush := TBrush.Create; // get a canvas to draw - this is a canvas for the complete listbox! with (Control as TListBox).Canvas do begin // put out lines in alternating colors if (index mod 2)=0 then ListColor := clSilver else ListColor := clBlue; ListBrush.Style := bsSolid; ListBrush.Color := ListColor; Windows.FillRect(Handle, Rect, ListBrush.Handle); Brush.Style := bsClear; // write out the text TextOut(Rect.Left, Rect.Top, (Control as TListBox).Items[index]); ListBrush.Free end; { with (Control as TListBox).Canvas } end; end.