代码之家  ›  专栏  ›  技术社区  ›  Cory

win32-lb-gettex返回垃圾

  •  4
  • Cory  · 技术社区  · 16 年前

    我有一个问题,这很可能是一个简单的问题,但对我来说,这仍然是一个问题。我在Win32/C++中使用ListBox,当从我的ListBox获得所选文本时,返回的字符串只是垃圾。它是结构或类似结构的句柄?

    下面是我得到的代码和示例。

    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”,它返回了“test string”。

    任何帮助都是表面化的,谢谢。

    好的,我把范围缩小到getSelected函数,因为getString返回正确的字符串。

    1 回复  |  直到 13 年前
        1
  •  10
  •   Andrew Grant    16 年前

    lb_getsel消息不返回所选项目的索引,它返回在wparam中传递的项目的所选状态。

    您还有一个严重的bug,如果没有选择任何项,您将尝试在索引-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获取所选项目的列表。