Author: Tomas Rutkauskas
I have a listbox on a form which contains a list of stuff of varying widths. In
some situations, they all fit in the box, in some cases the entries are too long to
fit and their right end gets cropped. Is there some way to force the listbox to set
a horizontol scrollbar if and only if an entry is being cropped? I can brute force
set the ScrollWidth property to 1000, but this puts a scrollbar in place all the
time. I only want a scrollbar if it's necessary.
Answer:
1 { ... }2 listbox.Scrollwidth := CalcMaxWidthOfStrings(listbox.Items, listbox.font);
3 { ... }4 5 function CalcMaxWidthOfStrings(aList: TStrings; aFont: TFont): Integer;
6 var7 max, n, i: Integer;
8 canvas: TCanvas;
9 begin10 Assert(Assigned(aList));
11 Assert(Assigned(aFont));
12 canvas := TCanvas.Create;
13 try14 canvas.Handle := CreateDC('DISPLAY', nil, nil, nil);
15 try16 Canvas.Font := aFont;
17 max := 0;
18 for i := 0 to aList.Count - 1 do19 begin20 n := Canvas.TextWidth(aList[i]);
21 if n > max then22 max := n;
23 end;
24 Result := max;
25 finally26 DeleteDC(canvas.Handle);
27 canvas.Handle := 0;
28 end;
29 finally30 canvas.free;
31 end;
32 end;