Win32 LB_GETTEXT returns garbage

I have a problem, which is most likely a simple problem, but nonetheless a problem for me. I use Listbox in Win32 / C ++, and getting the selected text from my list, the returned string is just rubbish. Is this a handle to a structure or the like?

Below is the code and an example of what I get.

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 just does it. It just gets the number of items in the list.

The string I grabbed from the Listbox is "Test String" and it returned ¨ ± é "Tzã

Any help is approximated, thanks.

Ok, I narrowed it down to my GetSelected function since GetString returns the correct string.

+3
source share
1

LB_GETSEL , , WPARAM.

, , , -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 .

+9

Source: https://habr.com/ru/post/1706253/