How to display icons in a combo box #200

Each combo box item with own its icon? No problem. Using the owner-draw style we can do almost anything.

Place a TComboBox and a TImageList on a form. Fill the image list with icons that are to be displayed in the combo box. Set the Style property of the combo box to csOwnerDrawFixed or csOwnerDrawVariable. The final step is to add a OnDrawItem event handler to the combo box.

Here's the code:

unit Unit1;
 
interface
 
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ImgList, StdCtrls;
 
type
  TForm1 = class(TForm)
    ComboBox1: TComboBox;
    ImageList1: TImageList;
    procedure ComboBox1DrawItem(Control: TWinControl; Index: Integer;
      Rect: TRect; State: TOwnerDrawState);
  end;
 
var
  Form1: TForm1;
 
implementation
 
{$R *.dfm}
 
procedure TForm1.ComboBox1DrawItem(Control: TWinControl; Index: Integer;  
  Rect: TRect; State: TOwnerDrawState);
var
  ComboBox: TComboBox;
  bitmap: TBitmap;
begin
  ComboBox := (Control as TComboBox);
  Bitmap := TBitmap.Create;
  try
    ImageList1.GetBitmap(Index, Bitmap);
    with ComboBox.Canvas do
    begin
      FillRect(Rect);
      if Bitmap.Handle <> 0 then 
        Draw(Rect.Left + 2, Rect.Top, Bitmap);
      Rect := Bounds(
        Rect.Left + ComboBox.ItemHeight + 2,
        Rect.Top,
        Rect.Right - Rect.Left, 
        Rect.Bottom - Rect.Top
      );
      DrawText(
        handle, 
        PChar(ComboBox.Items[Index]), 
        length(ComboBox.Items[index]), 
        Rect, 
        DT_VCENTER + DT_SINGLELINE
      );
    end;
  finally
    Bitmap.Free;
  end;
end;
 
end.

Description revised by DelphiDabbler

Author: Unknown
Contributor: topellina
Added: 2012/09/17
Last updated: 2012/09/17