Drawing icons or bitmaps in a ComboBox or ListBox 

In this example, we'll utilize the diversity of an ImageList to help us draw graphics in a ListBox.  This code applies to ComboBoxes as well. The Combo/ListBox must be owner-drawn (i.e., the Style property set to xxOwnerDrawFixed or xxOwnerDrawVariable, where xx = cs for ComboBoxes or xx= lb for ListBoxes)

The example below uses a separate TImageList to render an image next to each ListBox item.
 

KEYWORDS: owner-drawn, TextOut, TImageList 



 

//in header file 
private:
    int MyIconMapper[1000]; 

 


 
 

//---------------------------------------------------------------------------

// MyIconMapper will define what icons in the 
// ImageList correspond to what items in the ListBox.

// Any suitable object/structure can be used for the mapping; 
// here we'll use a simple array...

__fastcall TForm1::TForm1(TComponent* Owner) 
        : TForm(Owner) 

    MyIconMapper[0] = 1; //ImageList image index 1 for ListBox item 0
    MyIconMapper[1] = 0; //ImageList image index 0 for ListBox item 1
    MyIconMapper[2] = 1; //ImageList image index 1 for ListBox item 2 
    // and so on... 

 
 

// The OnDrawItem event is used to render the item's text 
// and the icon/bitmap for each item...

void __fastcall TForm1::ListBox1DrawItem(TWinControl *Control, 
    int Index, TRect &Rect, TOwnerDrawState State)
{
    // eliminate artifacts
    ListBox1->Canvas->FillRect(Rect);

    if (State.Contains(odSelected))
    {
        ListBox1->Canvas->Font->Color = clWhite;
        ListBox1->Canvas->Brush->Color = clNavy;
    }

    // draw the icon or bitmap
    ImageList1->Draw(ListBox1->Canvas, Rect.Left, Rect.Top, MyIconMapper[Index]);

    // render the item's text
       int offset = ImageList1->Width + 2;
    ListBox1->Canvas->TextOut(Rect.Left + offset, Rect.Top, 
                              ListBox1->Items->Strings[Index]);

}