我有一个问题,很可能是一个简单的问题,但对我来说仍然是一个问题。我在 Win32 / C++ 中使用列表框,当从列表框中获取选定的文本时,返回的字符串只是垃圾。它是结构或类似结构的句柄?
下面是代码和我得到的示例。
std::string Listbox::GetSelected() {
int index = -1;
int count = 0;
count = SendMessage(control, LB_GETSELCOUNT, 0, 0);
if(count > 0) {
index = SendMessage(control, LB_GETSEL, 0, 0);
}
return GetString(index);
}
std::string Listbox::GetString(int index) {
int count = 0;
int length = 0;
char * text;
if(index >= 0) {
count = GetItemCount();
if(index < count) {
length = SendMessage(control, LB_GETTEXTLEN, (WPARAM)index, 0);
text = new char[length + 1];
SendMessage(control, LB_GETTEXT, (WPARAM)index, (LPARAM)text);
}
}
std::string s(text);
delete[] text;
return s;
}
GetItemCount 就是这样做的。它只是获取列表框中当前的项目数。
我从列表框中抓取的字符串是“Test String”,它返回了“Tzã”
如有任何帮助,我们将不胜感激,谢谢。
好的,我将范围缩小到 GetSelected 函数,因为 GetString 返回正确的字符串。
LB_GETSEL 消息不返回所选项目的索引,它返回您在 WPARAM 中传递的 ITEM 的所选状态。
您还有一个严重的错误,如果没有选择任何项目,您将尝试检索索引 -1 处的项目的字符串,这显然是错误的。检查这些 SendMessage 调用的返回值将有助于您诊断问题。
以下是如何获取第一个选定项目的文本的示例;
// get the number of items in the box.
count = SendMessage(control, LB_GETCOUNT, 0, 0);
int iSelected = -1;
// go through the items and find the first selected one
for (int i = 0; i < count; i++)
{
// check if this item is selected or not..
if (SendMessage(control, LB_GETSEL, i, 0) > 0)
{
// yes, we only want the first selected so break.
iSelected = i;
break;
}
}
// get the text of the selected item
if (iSelected != -1)
SendMessage(control, LB_GETTEXT, (WPARAM)iSelected , (LPARAM)text);
或者,您可以使用 LB_GETSELITEMS 获取所选项目的列表。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)