首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> VC 教學

C++ Builder 結合 Windows API 擴充 ComboBox 自動完成功能

     編輯:VC 教學

需求

標準 TComboBox 在 OnChange 事件中預設不支援「輸入部分字串自動匹配下拉項目並選中剩餘部分」的行為。需結合 CB_FINDSTRING、CB_SETEDITSEL 訊息實現。

實作步驟

  1. 表單放置 TComboBox (名為 ComboBox1),Items 加入範例字串。
  2. 建立 OnChange 事件:
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));
    }
}
  1. 建立 OnKeyDown 事件記錄最後按鍵:
void __fastcall TForm1::ComboBox1KeyDown(TObject *Sender, WORD &Key, TShiftState Shift)
{
    LastKey = Key;
}
  1. 表單類別私有區宣告 WORD LastKey;。

效果

使用者輸入 "Chi" → 自動匹配 "China" 並選中 "na" 部分,游標停留在 "Chi" 後,繼續輸入可進一步縮小範圍。此技巧利用 Windows 原生 ComboBox 訊息,無需自繪或第三方元件。

適用環境

Win98 + C++ Builder 4.0 Enterprise 測試通過。同理可移植至 Delphi (換語法)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved