[VC]得到/设置DropDown ComboBox的文字

博客介绍了使用DropDown类型的ComboBox时,若输入非列表值,GetCurSel()为CB_ERR,相关函数无法工作。还给出了获取和设置ComboBox文字的方法,包括GetComboBoxString函数获取文字,SetComboBoxString函数设置文字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用DropDown类型的ComboBox时,如果使用者输入非ComboBox中列出的值,那么ComboBox的GetCurSel()的值是CB_ERR,相关的GetLBText()和GetLBTextLen()因为没有index也就无法工作。

在DDX时,可以把ComboBox和CString对应起来,采用它的原理,就可以自己来得到或设置DropDown ComboBox的文字了。

//得到ComboBox的文字
void GetComboBoxString(HWND hWndCtrl, CString& value)
{
    // just get current edit item text (or drop list static)
    int nLen = ::GetWindowTextLength(hWndCtrl);
    if (nLen > 0)
    {
        // get known length
        ::GetWindowText(hWndCtrl, value.GetBufferSetLength(nLen), nLen+1);
    }
    else
    {
        // for drop lists GetWindowTextLength does not work - assume
        //  max of 255 characters
        ::GetWindowText(hWndCtrl, value.GetBuffer(255), 255+1);
    }
    value.ReleaseBuffer();
}

//设置ComboBox的文字
void SetComboBoxString(HWND hWndCtrl, const CString& value)
{
    // set current selection based on model string
    OutputDebugString("SetComboBoxString:" + value);
    if (::SendMessage(hWndCtrl, CB_SELECTSTRING, (WPARAM)-1,
        (LPARAM)(LPCTSTR)value) == CB_ERR)
    {
        // just set the edit text (will be ignored if DROPDOWNLIST)
        AfxSetWindowText(hWndCtrl, value);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值