Mega Code Archive

 
Categories / Delphi / VCL
 

TListBox Ellipsis (without creating a new component)

Title: TListBox Ellipsis (without creating a new component) Question: How do you modify an existing TListBox, adding an ellipsis (...) to item strings that are too long to fit within the control, without creating a new component? Answer: This fast and simple way utilizes Borland's own DrawItem code, with a simple modification to incorporate an additional WinAPI flag: DT_END_ELLIPSIS Steps taken: 1. Change the TListBox.Style to lbOwnerDrawFixed (causes OnDrawItem event to fire) 2. Modify the TListBox.OnDrawItem event as follows procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var Flags: Longint; begin with TListBox(Control) do begin Canvas.FillRect(Rect); if Index then begin Flags := DrawTextBiDiModeFlags(DT_SINGLELINE or DT_VCENTER or DT_NOPREFIX or DT_END_ELLIPSIS); if not UseRightToLeftAlignment then Inc(Rect.Left, 2) else Dec(Rect.Right, 2); DrawText(Canvas.Handle, PChar(Items[Index]), Length(Items[Index]), Rect, Flags); end; end; end; Additionally, if an item string contains backslash characters, you can use the DT_PATH_ELLIPSIS flag to replace characters in the middle of the string (commonly used with long filenames).