将组合框中的类型字符串与其项目进行比较

compare typed string in a combobox with its items

本文关键字:项目 比较 字符串 组合 类型      更新时间:2023-10-16

假设我有 20 个不同长度的字符串,每个字符串都应该得到类似于以下内容:

TCHAR *itemText[...];
SendMessage(hwndCombobox, CB_GETLBTEXT, i, (LPARAM)itemText);

由于我有项目的索引,我想在 for 循环中使用上面的代码。但是因为每个项目都有不同的长度,所以我不能使用这样的东西:

int itemLength = SendMessage(hwndCombobox, CB_GETLBTEXTLEN, i, 0);
TCHAR *itemText[itemLength];

由于首先使用消息CB_GETLBTEXTLEN需要长度,因此有必要获取长度。我知道我可以使用,例如,TCHAR *itemText[1024];,但我个人不喜欢这种方式。

我也尝试使用newdelete,其他人建议我将vectorstd::string一起使用,就像这篇文章中一样 删除 new 在回调函数中创建的指针,但这导致了另一个问题,因为CB_GETLBTEXT所需的 LPARAM 参数需要A pointer to the buffer that receives the string.,所以下面的代码不起作用, 由于最后一个参数是 std::string ,而不是接收字符串的指针:

int i;
Vec<std::string> itemText;
for (i = 0; i < itemCount; i++) {
    ......... // Don't know how to initialize a string with a specified length.
    SendMessage(win->hwndFindBox, CB_GETLBTEXT, i, (LPARAM)itemText.At(i));
}

我也不知道如何初始化具有指定长度的std::string str

实际上,我想将组合框控件的编辑控件中的键入字符串与此组合框上的项进行比较。你有什么建议来解决这个问题或做我想做的事情吗?

您可能误解了将std::vectorstd::string一起使用的建议。 读取 ComboBox 项文本时,应使用 std::vector<TCHAR> 作为临时缓冲区(因为不能直接写入 std::basic_string 使用的内部缓冲区(,然后如果需要,可以将其复制到std::basic_string<TCHAR>中:

std::basic_string<TCHAR> s;
int itemLength = SendMessage(hwndCombobox, CB_GETLBTEXTLEN, i, 0);
if (itemLength != CB_ERR)
{
    std::vector<TCHAR> buf(itemLength + 1 /* for NUL */);
    SendMessage(hwndCombobox, CB_GETLBTEXT, i, reinterpret_cast<LPARAM>(&buf[0]));
    s = &buf[0];
}

这是有效的,因为std::vector保证使用连续内存,因此&buf[0]应该等效于数组(假设buf不为空,但在这种情况下,我们保证它至少有 1 个元素(。