How to include bitmaps in a listbox
Back to How to index
Basic steps
- Place a normal listbox on the form.
- Set the Style property to lbOwnerDrawFixed.
- Add an OnDrawItem event handler (double-click the OnDrawItem property on the Events tab of the Object Inspector)
- Write the code for drawing the item -- see below.
Code
procedure TForm1.ListDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
var
Offset, Y, W, H: Integer; ImageNumber: Integer;
begin
if not (csDestroying in ComponentState) then
with (Control as TListBox).Canvas do
begin
FillRect(Rect);
Offset := 2;
W := SmallImages.Width;
ImageNumber := 0;
SmallImages.Draw(TListbox(Control).Canvas, Rect.Left + Offset,
Rect.Top, ImageNumber, True);
H := (Rect.Bottom - Rect.Top) + 1;
Y := Rect.Top + (H div 2) - (TextHeight('Ag') div 2);
Offset := Offset + W;
TextOut(Rect.Left + Offset, Y, TListBox(Control).Items[Index]);
end;
end;