如何在 CComboBoxEx 中获取当前选中的文本?

How to get the currently selected text in a CComboBoxEx?

我解决这个问题的第一个方法是在 CComboBoxEx control, but I found that there is no associated text. After analyzing the control with Spy++ and reading some documentation on CComboBoxEx, I realised that these type of controls are only the parent of a classic ComboBox:

上调用 GetWindowsText 方法

我尝试使用 GetLBText() method on the child ComboBox, passing GetCurSel() 作为参数,但我只得到了一些错误的文本(正确的文本应该是 "English"):

我错过了什么吗?提前致谢!

最后我设法找回了正确的名字;如下图所示,ComboBox 只是 CombBoxEx32:

的 child

我从 child ComboBox 中检索到指向 parent ComboBoxEx32 的指针,并以这种方式搜索文本:

CString szText;
CComboBoxEx cbParentCombo ;
cbParentCombo.Attach( GetParent()->GetSafeHwnd()) ;
cbParentCombo.GetLBText( GetCurSel(), szText) ;
cbParentCombo.Detach() ;

我的错误是我直接从 child ComboBox 调用 GetLBText(),而不是 parent CComboBoxEx;因此,我得到的只是一些随机的胡言乱语。 GetLBText() 确实是正确的解决方案。

您要做的是使用 Class 向导将控件映射到 int 变量:

现在可以随时轻松访问所选文本。您需要使用 GetItem 函数。例如(代码未测试):

COMBOBOXEXITEM cmbItem;
CString strText;

cmbItem.mask = CBEIF_TEXT;
cmbItem.iItem = m_cbItemIndex;
cmbItem.pszText = strText.GetBuffer(_MAX_PATH);
m_cbMyCombo.GetItem(&cmbItem);
strText.ReleaseBuffer();

简而言之,您需要使用 COMBOBOXEXITEM 并使用正确的标志对其进行初始化,以说明您希望从扩展组合中获取哪些信息。那,和项目索引。任务完成!


我知道你有自己的继承class,但机制是一样的。你不使用 GetLBText。您使用带有索引和 GetItem 的结构来获取选定的文本。