下面是一个完整的例子:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls;
type
TForm1 = class(TForm)
Panel1: TPanel;
ListBox1: TListBox;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure ListBox1Enter(Sender: TObject);
private
MaxWidth:Integer;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
i:integer;
begin
MaxWidth:=0;
for i:=1 to 20 do
begin
ListBox1.Items.Add('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA');
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var i: integer;
begin
for i := 0 to ListBox1.Items.Count - 1 do
if MaxWidth < ListBox1.Canvas.TextWidth(ListBox1.Items) then
MaxWidth := ListBox1.Canvas.TextWidth(ListBox1.Items);
SendMessage(ListBox1.Handle, LB_SETHORIZONTALEXTENT, MaxWidth+2, 0);
end;
procedure TForm1.ListBox1Enter(Sender: TObject);
{var i: integer;}
begin
{ 在这里使用ListBox将自动出现水平滚动条 }
{ for i := 0 to ListBox1.Items.Count - 1 do
if MaxWidth < ListBox1.Canvas.TextWidth(ListBox1.Items) then
MaxWidth := ListBox1.Canvas.TextWidth(ListBox1.Items);
SendMessage(ListBox1.Handle, LB_SETHORIZONTALEXTENT, MaxWidth+2, 0);}
end;
end.