DropDown 型別的 ComboBox 允許使用者輸入清單外文字。此時 GetCurSel() 回傳 CB_ERR,導致 GetLBText() 無法運作。需直接從編輯控件取得/設定文字。
MFC 的 DDX_CBString 內部即透過 GetWindowText/SetWindowText 處理此情況,參考其原理封裝通用函式。
void GetComboBoxString(HWND hWndCtrl, CString& value)
{
int nLen = ::GetWindowTextLength(hWndCtrl);
if (nLen > 0) {
::GetWindowText(hWndCtrl, value.GetBufferSetLength(nLen), nLen + 1);
} else {
// DropDownList 模式下 GetWindowTextLength 可能回傳 0
::GetWindowText(hWndCtrl, value.GetBuffer(255), 256);
}
value.ReleaseBuffer();
}
void SetComboBoxString(HWND hWndCtrl, const CString& value)
{
OutputDebugString("SetComboBoxString:" + value);
// 嘗試在清單中尋找匹配項目並選取
if (::SendMessage(hWndCtrl, CB_SELECTSTRING, (WPARAM)-1, (LPARAM)(LPCTSTR)value) == CB_ERR) {
// 清單無匹配:直接設定編輯控件文字(DropDownList 模式會被忽略)
AfxSetWindowText(hWndCtrl, value);
}
}
DDX 情境下需存取 DropDown ComboBox 目前顯示文字。