How to force a TListBox to set a horizontol scrollbar if an entry is being cropped (Views: 29)
Problem/Question/Abstract: 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: { ... } listbox.Scrollwidth := CalcMaxWidthOfStrings(listbox.Items, listbox.font); { ... } function CalcMaxWidthOfStrings(aList: TStrings; aFont: TFont): Integer; var max, n, i: Integer; canvas: TCanvas; begin Assert(Assigned(aList)); Assert(Assigned(aFont)); canvas := TCanvas.Create; try canvas.Handle := CreateDC('DISPLAY', nil, nil, nil); try Canvas.Font := aFont; max := 0; for i := 0 to aList.Count - 1 do begin n := Canvas.TextWidth(aList[i]); if n > max then max := n; end; Result := max; finally DeleteDC(canvas.Handle); canvas.Handle := 0; end; finally canvas.free; end; end; |