Mega Code Archive

 
Categories / Delphi / VCL
 

A Smart Combo match search

Title: A "Smart Combo" match search Question: How to make to your combo box searches for the best match when you are typing ? Answer: now here is a method to force the combo box to search for the best match for the input you are typing: // define this variable LastKeyPressed: Word; procedure TForm1.ComboBox1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin LastKeyPressed := Key; // save the last key you pressed end; procedure TForm1.ComboBox1Change(Sender: TObject); Var ComboText : String; NewComboText : String; matchindex : integer; begin ComboText := ComboBox1.Text; // give the user the ability to delete the text; if (LastKeyPressed = VK_DELETE) OR (LastKeyPressed = 8 ) then begin LastKeyPressed := 0; end else begin if ComboBox1.SelStart length (ComboText) then // to make sure that in this moment the user is just beginning to type // do nothing here , because he can type any thing he want in the middle of the text else begin // find the match matchindex := sendmessage ( ComboBox1.Handle, CB_FINDSTRING , -1, LPARAM(ComboText) ) ; if matchindex = 0 then begin ComboBox1.ItemIndex := matchindex ; NewComboText := ComboBox1.Text; // highlight the other part of the text: sendmessage ( ComboBox1.Handle, CB_SETEDITSEL , 0, MAKELPARAM(length(ComboText) , word(-1) )); end; end; end; // NOTE: This code was tested on delphi 4, Windows NT workstation 4