Placing A Bitmap Image in a Control in a Windows VCL Application

From RAD Studio
Jump to: navigation, search

Go Up to How To Build a Windows VCL Application with Graphics

This procedure adds a bitmap image to a combo box in a VCL forms application.

  1. Create a VCL form.
  2. Place components on the form.
  3. Set component properties in the Object Inspector.
  4. Write event handlers for the component's drawing action.
  5. Build and run the application.

To create a VCL form with a TComboBox component

  1. Open File > New > Windows VCL Application - Delphi
  2. From the Win32 page of the Tool Palette, place an TImageList component on the form.
  3. From the Standard page of the Tool Palette, place a TComboBox on the form.

To set the component properties

  1. Select ComboBox1 in the form.
  2. In the Object Inspector, set the Style property drop-down to csOwnerDrawFixed.
  3. In the Object Inspector, click the ellipsis next to the Items property.The String List Editor displays.
  4. Enter a string you would like to associate with the bitmap image, for example, MyImage; then click OK.
  5. Double-click ImageList1 in the form.The ImageList editor displays.
  6. Click the Add button to display the Add Images dialog.
  7. Locate a bitmap image to display in the Combo box.To locate an image, you can search for *.bmp images on your local drive. Select a very small image such as an icon. Copy it to your project directory, and click Open.The image displays in the ImageList editor.
  8. Click OK to close the editor.

To add the event handler code

  1. In the VCL form view, select ComboBox1.
  2. In the Object Inspector, click the Events page, and double-click the OnDrawItem event.The Code Editor displays with cursor in the code block of the ComboBox1DrawItem (Delphi) or ComboBox1::DrawItem (C++) event handler.
  3. Enter the following code for the event handler:
Combobox1.Canvas.FillRect(Rect);
ImageList1.Draw(ComboBox1.Canvas, Rect.Left, Rect.Top, Index);
Combobox1.Canvas.TextOut(Rect.Left+ImageList1.Width+2,
  Rect.Top, ComboBox1.Items[Index]);
ComboBox1->Canvas->FillRect( Rect );
ImageList1->Draw( ComboBox1->Canvas, Rect.Left, Rect.Top, Index );
ComboBox1->Canvas->TextOut( Rect.Left + ImageList1->Width + 2,
                            Rect.Top,
                            ComboBox1->Items[Index] );

To run the program

  1. Choose Run > Run .The applications executes, displaying a form with a combo box.
  2. Click the combo box drop-down.The bitmap image and the text string display as a list item.

See Also