我正在尝试研究如何在TListBox上设置ScrollWidth来控制水平滚动条.这是我的第一次尝试:
program ListBoxSizing; uses Math,Forms,StdCtrls; var Form: TForm; ListBox: TListBox; procedure BuildForm; begin //Form.Font.Size := 9; Form.ClientWidth := 200; Form.ClientHeight := 100; ListBox := TListBox.Create(Form); ListBox.Parent := Form; ListBox.SetBounds(0,Form.ClientWidth,Form.ClientHeight); ListBox.Items.Add('ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ'); end; procedure SetScrollWidth; var i,MaxWidth: Integer; begin MaxWidth := -1; for i := 0 to ListBox.Items.Count-1 do MaxWidth := Max(MaxWidth,ListBox.Canvas.TextWidth(ListBox.Items[i])); if MaxWidth<>-1 then ListBox.ScrollWidth := MaxWidth; end; begin Application.MainFormOnTaskbar := True; Application.CreateForm(TForm,Form); BuildForm; SetScrollWidth; Application.Run; end.
这是水平滚动条尽可能向右移动的结果:
注意最终字符的最后部分是如何被切断的.
现在,如果我们取消注释更改表单字体大小的行,它看起来像这样:
现在,似乎在后续的TextWidth调用中没有考虑到字体大小的变化.
解决方法
procedure SetScrollWidth; var I,MaxWidth: Integer; begin MaxWidth := -1; // assign control's font to canvas ListBox.Canvas.Font := ListBox.Font; for I := 0 to ListBox.Items.Count - 1 do MaxWidth := Max(MaxWidth,ListBox.Canvas.TextWidth(ListBox.Items[I])); // consider non-client area if MaxWidth <> -1 then ListBox.ScrollWidth := MaxWidth + ListBox.Width - ListBox.ClientWidth; end;