2009. május 3., vasárnap

How to draw a bitmap between the checkbox and the label in a TCheckListBox


Problem/Question/Abstract:

How to draw a bitmap between the checkbox and the label in a TCheckListBox

Answer:

This should do the trick. It is also possible to place a bitmap in the middle, i.e. The checkbox, then some text, the graphic, then more text, on the same line. The Checklistbox style must be set to lbOwnerDrawVariable for this to work.

procedure TForm1.Button2Click(Sender: TObject);
begin
  {Bit1 is called from a resource file}
  CheckListBox1.Items.AddObject('Test this bitmap', Bit1);
end;

procedure TForm1.CheckListBox1DrawItem(Control: TWinControl; Index: Integer;
  Rect: TRect; State: TOwnerDrawState);
var
  Bitmap: TBitmap;
  Offset: Integer;
begin
  Offset := 12;
  with (Control as TCheckListBox).Canvas do
  begin
    FillRect(Rect);
    Bitmap := TBitmap(CheckListBox1.Items.Objects[Index]);
    if Bitmap <> nil then
    begin
      BrushCopy(Bounds(Rect.Left + 2, Rect.Top + 2, Bitmap.Width, Bitmap.Height),
        Bitmap, Bounds(0, 0, Bitmap.Width, Bitmap.Height), clRed);
      Offset := Bitmap.width + 8;
    end;
    TextOut(Rect.Left + Offset, Rect.Top, CheckListbox1.Items[Index])
  end;
end;

procedure TForm1.CheckListBox1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  height := 16;
end;

Nincsenek megjegyzések:

Megjegyzés küldése