TMyListBox =
class(TListBox)
private
fFilter:
String;
fLastTime: Cardinal;
fkeypresstime: Integer;
protected
procedure KeyPress(
var Key: Char);
override;
public
constructor Create(AOwner: TComponent);
override;
published
property Keypresstime: Integer
read fKeypresstime
write fkeypresstime;
end;
[...]
constructor TMyListBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fkeypresstime := 10000;
FFilter := '
';
FLastTime := GetTickCount;
end;
procedure TMyListBox.KeyPress(
var Key: Char);
procedure FindString;
var
Idx: Integer;
begin
if Style
in [lbVirtual, lbVirtualOwnerDraw]
then
Idx := DoFindData(FFilter)
else
Idx := SendMessage(
Handle, LB_FINDSTRING, -1, LongInt(PChar(FFilter)));
if Idx <> LB_ERR
then
begin
if MultiSelect
then
begin
ClearSelection;
SendMessage(
Handle, LB_SELITEMRANGE, 1, MakeLParam(Idx, Idx))
end;
ItemIndex := Idx;
Click;
end;
if not (Ord(Key)
in [VK_RETURN, VK_BACK, VK_ESCAPE])
then
Key := #0;
// Clear so that the listbox's default search mechanism is disabled
end;
var
Msg: TMsg;
begin
inherited KeyPress(Key);
if not AutoComplete
then exit;
if GetTickCount - FLastTime >= fkeypresstime
then
FFilter := '
';
FLastTime := GetTickCount;
if Ord(Key) <> VK_BACK
then
begin
if Key
in LeadBytes
then
begin
if PeekMessage(Msg,
Handle, WM_CHAR, WM_CHAR, PM_REMOVE)
then
begin
FFilter := FFilter + Key + Chr(Msg.wParam);
Key := #0;
end;
end
else
FFilter := FFilter + Key;
end
else
begin
while ByteType(FFilter, Length(FFilter)) = mbTrailByte
do
Delete(FFilter, Length(FFilter), 1);
Delete(FFilter, Length(FFilter), 1);
end;
if Length(FFilter) > 0
then
FindString
else
begin
ItemIndex := 0;
Click;
end;
end;