抄别人的.
unit AutoListComboBox;
interface
uses
SysUtils, Classes, Controls, StdCtrls, Messages;
type
TAutoListComboBox = class(TComboBox)
private
{ Private declarations }
FText:String;
FAllStrings:TStrings; //用来保存所有的字符串
procedure SetStrings(const value:TStrings);
protected
{ Protected declarations }
procedure DoEnter;override; //覆盖事件 DoEnter,当控件获得焦点时,作一些初始化工作
procedure KeyPress(var Key:Char);override; //覆盖事件 KeyPress, 打开自动下拉列表
procedure Change;override; //当用户键入字符导致Text变化时,改变Items包含的字符串
public
{ Public declarations }
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
published
{ Published declarations }
property AllStrings:TStrings read FAllStrings write SetStrings;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Zhuangquanmin', [TAutoListComboBox]);
end;
{ TAutoListComboBox }
//局部过程 PackStrings 用来去掉字符列表里面的重复项
procedure PackStrings(Strs:TStrings);
var
i:integer;
s:string;
begin
if Strs.Count=0 then
exit;
//将更新的操作放入BegindUpdate 和EndUpdate之间,可以避免TStrings的一些事件发生,从而提高处理速度
Strs.BeginUpdate;
with TStringList(Strs) do //这儿转化的目的是为了使用TStringList的排序功能
begin
Sort;
s:=Strings[0];
i:=1;
while i<Count do
begin
if s=Strings then
Delete(i)
else
begin
s:=Strings;
Inc(i);
end;
end;
end;
Strs.EndUpdate;
end;
procedure TAutoListComboBox.Change;
var
i,iSelStart:integer;
iWidth,MaxWidth,IndexMaxWidth:Integer;
begin
inherited Change;
if Text='' then
begin
Items.Assign(FAllStrings);
Exit;
end;
FText:=Text;
iSelStart:=SelStart;
Items.Clear;
MaxWidth:=0;
IndexMaxWidth:=-1;
for i := 0 to FAllStrings.Count - 1 do
if Pos(FText,FAllStrings)>0 then
begin
Items.Add(FAllStrings);
iWidth:=Length(FAllStrings);
if iWidth>MaxWidth then
begin
MaxWidth:=iWidth;
Inc(IndexMaxWidth,MaxWidth);
end;
end;
//改变列表项显示的长度,以便可以完全显示最长的字符串
Perform(CB_SETDROPPEDWIDTH,Canvas.TextWidth(Items[IndexMaxWidth])+10,0);
if not DroppedDown then
DroppedDown:=true;
Text:=FText;
SelStart:=iSelStart;
Self.AutoDropDown:=True;
end;
constructor TAutoListComboBox.Create(AOwner: TComponent);
begin
inherited;
AutoComplete:=false; //关闭其默认属性
FAllStrings:=TStringList.Create;
end;
destructor TAutoListComboBox.Destroy;
begin
FreeAndNil(FAllStrings);
inherited;
end;
procedure TAutoListComboBox.DoEnter;
begin
inherited;
if FAllStrings.Count<>0 then
PackStrings(FAllStrings)
else
FAllStrings.Assign(Items);
end;
procedure TAutoListComboBox.KeyPress(var Key: Char);
begin
//如果用户键入的不是一些控制键,如:Esc,回车,Ctrl+C/V/X 等就不打开自动下拉列表
if not(Ord(Key) in [27,13,3,22,24]) then
if not DroppedDown then
DroppedDown:=true;
inherited;
end;
procedure TAutoListComboBox.SetStrings(const value: TStrings);
begin
if Assigned(FAllStrings) then
FAllStrings.Assign(value)
else
FAllStrings:=value;
end;
end.