MFC C++ CListBox 获取所选项目

MFC C++ CListBox get selected item

本文关键字:选项 项目 获取 C++ CListBox MFC      更新时间:2023-10-16

首先让我说我已经在寻找解决方案几天了......

我正在尝试获取列表框的选定项。这是我的代码:

CListBox * pList1 = (CListBox *)GetDlgItem(IDC_LIST1);
CString ItemSelected;
// Get the name of the item selected in the Sample Tables list box 
// and store it in the CString variable declared above 
pList1->GetText(pList1->GetCurSel(), ItemSelected);
MessageBox(ItemSelected, "TEST", MB_OK);

现在,当我尝试此操作时,我收到一条错误消息,指出"参数不连贯"

除了错误处理之外,您的代码看起来正常。此外,MessageBox参数看起来不正确。第一个参数的类型应为 HWND 。我相信这是你问题的根本原因。请改用 MFC 标准AfxMessageBox

CListBox * pList1 = (CListBox *)GetDlgItem(IDC_LIST1);
int nSel = pList1->GetCurSel();
if (nSel != LB_ERR)
{
    CString ItemSelected; 
    pList1->GetText(nSel, ItemSelected);
    AfxMessageBox(ItemSelected);
}

如果 CListBox 处于单选模式,CListBox::GetCurSel 将返回选定的索引。

如果 CListBox 处于多选模式,则应使用 CListBox::GetSelItems,它将返回索引列表。

您不能混合匹配功能。

并始终检查返回代码(正如其他人已经写的那样)。

如果您已经有一个数据成员 MyList(of classCListBox):

int nSel = MyList.GetCurSel();
    CString ItemSelected;
    if (nSel != LB_ERR)
    {
        MyList.GetText(nSel, ItemSelected);
    }

CWnd 类有一个不需要 HWND 参数的 MessageBox 函数。但是,是的,AfxMessageBox更易于使用,并且可以在MFC代码中的任何位置调用,而无需CWnd派生的对象。另外一个注意事项:如果在 MFC 代码中调用 WinAPI 函数(此处不需要,但在其他情况下可能),最好在它前面加上范围解析运算符,以避免任何混淆、错误和/或名称冲突(例如::MessageBox...)。

OP 代码中出现"参数无效"错误的一个可能原因是它在 UNICODE 构建配置中使用了 ANSI 字符串文本("TEST")。在这种情况下,必须使用UNICODE字符串文字(L"TEST")或更好的一点,使用_T宏(_T("TEST")),这使得可以在ANSI和UNICODE配置中构建。