首页  编辑  

Combox中显示多行文本

Tags: /超级猛料/VCL/(Check|List|ComBo)BOX/   Date Created:

Combox 中显示多行文本

{

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

 if (Index > -1) then  // Don't waste time with this on Index = -1

 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;