標準 TComboBox 於 OnChange 發送 CB_FINDSTRING 尋找匹配項目,若找到則發送 CB_SETEDITSEL 選取剩餘字元,形成自動完成效果。需配合 OnKeyDown 記錄按鍵避免 Delete/Backspace 觸發誤動作。
TComboBox (Name=ComboBox1) Items 加入範例字串。WORD LastKey;void __fastcall TForm1::ComboBox1Change(TObject *Sender)
{
String value = ComboBox1->Text;
if (LastKey == VK_BACK || LastKey == VK_DELETE) { // 忽略刪除鍵
LastKey = 0; return;
}
LastKey = 0;
if (ComboBox1->SelStart != value.Length()) return; // 游標不在尾端不處理
int index = SendMessage(ComboBox1->Handle, CB_FINDSTRING, -1,
(LPARAM)value.c_str());
if (index >= 0) {
ComboBox1->ItemIndex = index;
SendMessage(ComboBox1->Handle, CB_SETEDITSEL, 0,
MAKELPARAM(value.Length(), -1)); // 選取輸入後剩餘部分
}
}
void __fastcall TForm1::ComboBox1KeyDown(TObject *Sender, WORD &Key,
TShiftState Shift)
{
LastKey = Key;
}
使用者輸入 "Chi" 即自動補全為 "China" 並反白 "na" 部分,繼續輸入可替換反白部分。