Mega Code Archive

 
Categories / Delphi / VCL
 

Auto completion for TCombobox

Title: Auto completion for TCombobox Question: A smart and handy solution for the auto-complete feature in a TCombobox - works quite well with just a few lines of code. Answer: { A smart and handy solution, easy to understand and, easy to adapt for your personal requirements. Don't forget to set the 'Sorted' property of the TCombobox to true to avoid problems. } // Add this to the var section of your form: var lastKey: Word; // put the following lines in the OnChange event of the TCombobox procedure TForm1.AutoCompleteChange(Sender: TObject); var SearchStr: string; retVal: integer; begin // copy search pattern SearchStr := (Sender as TCombobox).Text; // backspace: VK_BACK or $08 if lastKey VK_BACK then begin retVal := (Sender as TCombobox).Perform(CB_FINDSTRING, -1, LongInt(PChar(SearchStr))); if retVal CB_Err then begin (Sender as TCombobox).ItemIndex := retVal; (Sender as TCombobox).SelStart := Length(SearchStr); (Sender as TCombobox).SelLength := (Length((Sender as TCombobox).Text) - Length(SearchStr)); end; // retVal CB_Err end; // lastKey VK_BACK // reset lastKey lastKey := 0; end; // put the following lines in the OnKeyDown event of the TCombobox procedure TForm1.AutoCompleteKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin lastKey := Key; end;