2009-04-10 104 views
3

我有一个问题,这很可能是一个简单的问题,但对我来说还不是一个问题。我在Win32/C++中使用列表框,并从列表框中获取选定的文本时,返回的字符串就是垃圾。它是一个结构或类似的句柄?Win32 LB_GETTEXT返回垃圾

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

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就是这么做的。它只是获取列表框中当前项目的数量。

我是从列表框抓取的字符串是“测试字符串”和它返回¨±é»TZA

任何帮助appericated,谢谢。

好吧,我缩小到我的GetSelected函数为GetString返回正确的字符串。

+0

你正在为ANSI或UNICODE编译吗? – 2009-04-10 22:49:15

+0

另外,SendMessage的返回是什么,它与预期的LB消息相比如何? – 2009-04-10 22:50:01

回答

8

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获得所选择的项目列表。