2007. szeptember 3., hétfő

How to create non-selectable separator lines in a TComboBox


Problem/Question/Abstract:

How to create non-selectable separator lines in a TComboBox

Answer:

Note that the Combobox1.Style is csOwnerDrawvariable.

procedure TForm1.FormCreate(Sender: TObject);
begin
  with combobox1 do
  begin
    items.add('Item 1');
    items.add('Item 2');
    items.addObject('Item 3', Pointer(1));
    Perform(CB_SetItemHeight, 2, ItemHeight + 5);
    items.add('Item 4');
    items.add('Item 5');
  end;
end;

procedure TForm1.ComboBox1MeasureItem(Control: TWinControl; Index: Integer;
  var Height: Integer);
begin
  Height := (Control as TCombobox).Itemheight;
end;

procedure TForm1.ComboBox1DrawItem(Control: TWinControl; Index: Integer;
  Rect: TRect; State: TOwnerDrawState);
var
  needsSeparator: Boolean;
begin
  with Control as TCombobox do
  begin
    needsSeparator := Assigned(Items.Objects[index]) and not (odComboBoxEdit in State);
    if needsSeparator then
      Rect.Bottom := Rect.Bottom - 5;
    Canvas.FillRect(Rect);
    Canvas.TextRect(Rect, Rect.Left + 2, Rect.Top, Items[index]);
    if needsSeparator then
    begin
      Rect.Top := Rect.Bottom;
      Rect.Bottom := Rect.Bottom + 5;
      Canvas.Brush.Color := color;
      Canvas.Pen.Color := font.Color;
      Canvas.Pen.Style := psSolid;
      Canvas.Fillrect(Rect);
      Canvas.MoveTo(rect.left, rect.top + 2);
      Canvas.LineTo(rect.right, rect.top + 2);
    end;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése