...Text mehrzeilig in einer TCombobox ausgeben (Alternative)?

Autor: Paul Earley

Kategorie: VCL

{
  My application needed a ComboBox whose selection choices were too long
  to fit on one line of a ComboBox. I wrote this "quick and dirty" multiline
  ComboBox to fill this need and thought others might want to have this code handy.

  Make sure that the ComboBox Style is set to csOwnerDrawVariable! The two events
  to respond to in csOwnerDrawVariable are MeasureItem and DrawItem.
}

procedure TForm1.ComboBox1MeasureItem(Control: TWinControl; Index: Integer;
  var Height: Integer);
var
  
ItemString: string;
  MyRect: TRect;
  MyImage: TImage;
  MyCombo: TComboBox;
begin
  
// Don't waste time with this on Index = -1
  
if (Index > -1) then
  begin
    
MyCombo := TComboBox(Control);
    // Create a temporary canvas to calculate the height
    
MyImage := TImage.Create(MyCombo);
    try
      
MyRect := MyCombo.ClientRect;
      ItemString := MyCombo.Items.Strings[Index];
      MyImage.Canvas.Font := MyCombo.Font;
      // Calc. using this ComboBox's font size
      
Height := DrawText(MyImage.Canvas.Handle, PChar(ItemString),
        - 1, MyRect, DT_CALCRECT or DT_WORDBREAK);
    finally
      
MyImage.Free;
    end;
  end;
end;

procedure TForm1.ComboBox1DrawItem(Control: TWinControl; Index: Integer;
  Rect: TRect; State: TOwnerDrawState);
var
  
ItemString: string;
begin
  
TComboBox(Control).Canvas.FillRect(Rect);
  ItemString := TComboBox(Control).Items.Strings[Index];
  DrawText(TComboBox(Control).Canvas.Handle, PChar(ItemString), - 1, Rect, DT_WORDBREAK);
end;


(*** Quote:SDC-Team *** see also http://www.swissdelphicenter.ch/de/showcode.php?id=742  ***)

 

printed from
www.swissdelphicenter.ch
developers knowledge base