【问题标题】:Win32 LB_GETTEXT returns garbageWin32 LB_GETTEXT 返回垃圾
【发布时间】:2009-04-10 22:45:48
【问题描述】:

我遇到的问题很可能是一个简单的问题,但对我来说仍然是个问题。我在 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 就是这样做的。它只是获取当前列表框中的项目数。

我从列表框中获取的字符串是“测试字符串”,它返回了 ¨±é» Tzã

如有任何帮助,谢谢。

好的,我将范围缩小到我的 GetSelected 函数,因为 GetString 返回了正确的字符串。

【问题讨论】:

  • 你是为 ANSI 还是 UNICODE 编译?
  • 另外,SendMessage 的返回值是多少,与预期的 LB 消息相比如何?
  • 那么 GetSelected 返回什么?你是如何缩小范围的?
  • ANSI。顺便说一句,我正在使用 Mingw。
  • 好吧,GetString 返回正确的字符串,但 GetSelected 返回垃圾字符串……但 GetSelected 只返回 GetString(index)。所以它可能仍然在 GetString 中。

标签: c++ string winapi listbox


【解决方案1】:

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 获取选定项目的列表。

【讨论】:

  • 非常感谢您澄清这一点,更改似乎效果很好。目前我在尝试从列表框中选择一个字符串之前检查以确保索引 >= 0。
猜你喜欢
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-04
  • 2015-06-27
  • 2016-07-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多