Советы по Delphi

Инкрементальный поиск в ListBox II


Я видел приложение, в котором ListBox позволял осуществлять инкрементальный поиск. При вводе очередного символа он позиционирует вас к первой ячейке, начало значения которой совпадает с введенным пользователем текстом, или выделяет все строки с текстом, содержащим введенный текст.

Как это осуществить на Delphi?

Здесь придется немного воспользоваться Win API. Установите свойство формы KeyPreview в True и сделайте примерно следующее:

    unit LbxSrch;
interface
uses


Windows, Messages, SysUtils, Classes, Controls, Forms, StdCtrls;
type TFrmLbxSrch = class(TForm) Edit1: TEdit; Edit2: TEdit; ListBox1: TListBox; Label1: TLabel; procedure FormKeyPress(Sender: TObject; var Key: Char); procedure ListBox1Enter(Sender: TObject); private { Private declarations } FPrefix: array[0..255] of char; public { Public declarations } end;
var FrmLbxSrch: TFrmLbxSrch;
implementation
{$R *.DFM}
procedure TFrmLbxSrch.FormKeyPress(Sender: TObject; var Key: Char); { Помните о том, что свойство KeyPreview должно быть установлено в True } var curKey: array[0..1] of char; ndx:    integer; begin if ActiveControl = ListBox1 then begin if key = #8 {Backspace (клавиша возврата)} then begin if FPrefix[0] <> #0 then begin FPrefix[StrLen(FPrefix) - 1] := #0; end end else begin curKey[0] := Key; curKey[1] := #0; StrCat(FPrefix, curKey); ndx := SendMessage(ListBox1.Handle, LB_FINDSTRING, -1, longint(@FPrefix)); if ndx <> LB_ERR then ListBox1.ItemIndex := ndx; end;
Label1.Caption := StrPas(FPrefix); Key := #0; end; end;
procedure TFrmLbxSrch.ListBox1Enter(Sender: TObject); begin FPrefix[0] := #0; Label1.Caption := StrPas(FPrefix); end;
end.

- Ralph Friedman [001115]



Содержание раздела