13 de fev. de 2007

Como fazer busca incremental num combobox?

Este exemplo mostra como fazer uma busca incremental num combobox.

1 procedure TSeuForm.SeuComboBoxKeyPress(Sender: TObject; var AKey: Char); 2 var 3 ComboBox: TComboBox; 4 TextoDigitado: string; 5 TextoSelecionado: string; 6 TextoDoItem: string; 7 Texto: string; 8 Achou: Boolean; 9 Inicio: Integer; 10 I: Integer; 11 begin 12 ComboBox := Sender as TComboBox; 13 14 // recupera o que foi digitado 15 16 Inicio := ComboBox.SelStart; 17 18 // trata a tecla 19 TextoDigitado := Copy(ComboBox.Text, 1, ComboBox.SelStart); 20 if AKey = Chr(VK_BACK) then begin 21 22 if ComboBox.SelLength = 0 then begin 23 24 Delete(TextoDigitado, Length(TextoDigitado), 1); 25 end; 26 end 27 else begin 28 TextoDigitado := TextoDigitado + AKey; 29 end; 30 31 TextoSelecionado := Copy(ComboBox.Text, 32 ComboBox.SelLength + ComboBox.SelStart + 1, MaxInt); 33 34 Texto := TextoDigitado + TextoSelecionado; 35 if Texto <> '' then begin 36 37 // atualiza a posição de início da seleção 38 if AKey = Chr(VK_BACK) then begin 39 40 if Inicio > 0 then begin 41 42 Dec(Inicio); 43 end; 44 end 45 else if AKey <> Chr(VK_BACK) then begin 46 47 Inc(Inicio); 48 end; 49 50 // descarta a tecla 51 AKey := #0; 52 53 if Inicio = 0 then begin 54 55 ComboBox.Text := ''; 56 ComboBox.ItemIndex := -1; 57 end 58 else begin 59 60 // busca o texto 61 62 Achou := False; 63 for I := 0 to Pred(ComboBox.Items.Count) do begin 64 65 TextoDoItem := Copy(ComboBox.Items[I], 1, Length(Texto)); 66 Achou := AnsiCompareText(TextoDoItem, Texto) = 0; 67 if Achou then begin 68 69 ComboBox.Text := ComboBox.Items[I]; 70 ComboBox.ItemIndex := I; 71 72 Break; 73 end; 74 end; 75 76 if Achou then begin 77 78 // destaca a parte não digitada da string 79 ComboBox.SelStart := Inicio; 80 ComboBox.SelLength := Length(ComboBox.Text) - Inicio; 81 end 82 else begin 83 84 // beepa para avisar que não encontrou 85 Beep; 86 end; 87 end; 88 end; 89 end;

Nenhum comentário: