unit OnDrawItem;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ImgList;

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    ImageList1: TImageList;
    procedure ListBox1DrawItem(Control: TWinControl; Index: Integer;
      Rect: TRect; State: TOwnerDrawState);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  MyList: TStringList;
  bitmap0, bitmap1, bitmap2: TBitmap;

implementation

{$R *.dfm}

// BeginExample: OnDrawItem
// Event: StdCtrls.TCustomListBox.OnDrawItem
// Property: StdCtrls.TCustomListBox.Canvas

// Warning: Need to call Destroy for all these classes (TBitmap, TStringList...).

// BeginCode
{
Here is a typical handler for an OnDrawItem event. In the
example, a list box with the lbOwnerDrawFixed style draws a
bitmap to the left of each string.
Select the TListBox and set the ItemHeight property to 32.
Select the ImageList and set the Layout Height and Width to
32.  Double click on the ImageList to load the images.  Be
sure to load in the correct order, logo2, Sunflower,
butterfly.
}
procedure TForm1.FormCreate(Sender: TObject);
begin
  MyList := TStringList.Create;
  bitmap0 := TBitmap.Create;
  bitmap1 := TBitmap.Create;
  bitmap2 := TBitmap.Create;
//  MyList.Add('Animal');
//  MyList.Add('Flowers');
//  MyList.Add('Butterfly');
//  ListBox1.Items.AddStrings(MyList);

  ImageList1.GetBitmap(0, bitmap0);
  ListBox1.Items.AddObject('Flowers', bitmap0);
  ImageList1.GetBitmap(1, bitmap1);
  ListBox1.Items.AddObject('Animal', bitmap1);
  ImageList1.GetBitmap(2, bitmap2);
  ListBox1.Items.AddObject('Butterfly', bitmap2);
end;

procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect:TRect; State: TOwnerDrawState);
var
  Bitmap: TBitmap;      { temporary variable for the item’s bitmap }
  Offset: Integer;      { text offset width }
begin
  Bitmap := TBitmap.Create;
  with (Control as TListBox).Canvas do  { draw on control canvas, not on the form }
  begin
    FillRect(Rect);       { clear the rectangle }
    Offset := 2;          { provide default offset }
    Bitmap := TBitmap((Control as TListBox).Items.Objects[Index]);  { get the bitmap }
    if Bitmap <> nil then
    begin
      BrushCopy(
        Bounds(Rect.Left + Offset, Rect.Top, Bitmap.Width, Bitmap.Height),
        Bitmap, 
        Bounds(0, 0, Bitmap.Width, Bitmap.Height), 
        clRed);  {render bitmap}
      Offset := Bitmap.width + 6;    { add four pixels between bitmap and text}
    end;
    TextOut(Rect.Left + Offset, Rect.Top, (Control as TListBox).Items[Index])  { display the text }
  end;
end;
// EndCode
// EndExample: OnDrawItem

procedure TForm1.FormDestroy(Sender: TObject);
begin
  MyList.Destroy;
  bitmap0.Destroy;
  bitmap1.Destroy;
  bitmap2.Destroy;
end;
end.
