RAD Studio
ContentsIndex
PreviousUpNext
Drawing Owner-draw Items

When an application needs to draw or redraw an owner-draw control, the operating system generates draw-item events for each visible item in the control. Depending on the control, the item may also receive draw events for the item as a part of the item. 

To draw each item in an owner-draw control, attach an event handler to the draw-item event for that control. 

The names of events for owner drawing typically start with one of the following:

  • OnDraw, such as OnDrawItem or OnDrawCell
  • OnCustomDraw, such as OnCustomDrawItem
  • OnAdvancedCustomDraw, such as OnAdvancedCustomDrawItem
The draw-item event contains parameters identifying the item to draw, the rectangle in which to draw, and usually some information about the state of the item (such as whether the item has focus). The application handles each event by rendering the appropriate item in the given rectangle. 

For example, the following code shows how to draw items in a list box that has bitmaps associated with each string. It attaches this handler to the OnDrawItem event for the list box:

procedure TFMForm.DriveTabSetDrawTab(Sender: TObject; TabCanvas: TCanvas;
  R: TRect; Index: Integer; Selected: Boolean);
var
  Bitmap: TBitmap;
begin
  Bitmap := TBitmap(DriveTabSet.Tabs.Objects[Index]);
  with TabCanvas do
  begin
     Draw(R.Left, R.Top + 4, Bitmap);  { draw bitmap }
     TextOut(R.Left + 2 + Bitmap.Width,  { position text }
     R.Top + 2, DriveTabSet.Tabs[Index]);  { and draw it to the right of the bitmap }
  end;
end;

 

void __fastcall TForm1::ListBox1DrawItem(TWinControl *Control, int Index,
  TRect &Rect, TOwnerDrawState State)
  TBitmap *Bitmap = (TBitmap *)ListBox1->Items->Objects[Index];
  ListBox1->Canvas->Draw(R.Left, R.Top + 2, Bitmap); // draw the bitmap
  ListBox1->Canvas->TextOut(R.Left + Bitmap->Width + 2, R.Top + 2,
    ListBox1->Items->Strings[Index]);        // and write the text to its right
}
Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
What do you think about this topic? Send feedback!