Mega Code Archive

 
Categories / Delphi / VCL
 

Add a horizontal scrollbar to TListBox

Title: Add a horizontal scrollbar to TListBox Question: Answer: Delphi's TListBox component automatically implements a vertical scrollbar. The scrollbar appears when the list box isn't tall enough to display all its items. However, the list box doesn't display a horizontal scrollbar when its items are wider than its width. Of course, there's a way for you to add the horizontal scrollbar. Add the following code to the OnCreate event of your form. procedure TForm1.FormCreate(Sender: TObject); var i, MaxWidth: integer; begin MaxWidth := 0; for i := 0 to LB1.Items.Count - 1 do if MaxWidth MaxWidth := LB1.Canvas.TextWidth(LB1.Items.Strings[i]); SendMessage(LB1.Handle, LB_SETHORIZONTALEXTENT, MaxWidth+2, 0); end; The code finds the width, in pixels, of the longest string in the list box. Then, it uses the LB_SETHORIZONTALEXTENT message to set the horizontal scrollable width, in pixels, of the list box. The two extra pixels added to MaxWidth help offset narrow characters from the right edge of the list box.