Title: How to add images to a listbox
Question: here is a tip on how to add an image beside every text in a listbox
Answer:
First, change the style property of your listbox to [ lbOwnerDrawVariable ]
this will allow you to draw in the listbox.
add 3 items in the listbox.
then add an image list with 3 images inside.
add these event handlers for the listbox.
procedure TForm1.ListBox3MeasureItem(Control: TWinControl; Index: Integer;
var Height: Integer);
begin
height := ImageList1.Height + 4;
end;
// now the real drawing begins here:
procedure TForm1.ListBox3DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
var
CenterText : integer;
begin
ListBox3.Canvas.FillRect (rect);
// now draw
ImageList1.Draw(ListBox3.Canvas,rect.Left + 4, rect.Top + 4, index );
// you have to center the text vertically besidethe bitmap, or it will appear a little heigher
CenterText := ( rect.Bottom - rect.Top - ListBox3.Canvas.TextHeight(text)) div 2 ;
ListBox3.Canvas.TextOut (rect.left + ImageList1.Width + 8 , rect.Top + CenterText,
ListBox3.Items.Strings[index]);
end;
now run and enjoy your new style listbox
// Note: this code is tested on Delphi 4 , Windows NT workstation 4