MFC C++ CListBox 获取所选项目
MFC C++ CListBox get selected item
首先让我说我已经在寻找解决方案几天了......
我正在尝试获取列表框的选定项。这是我的代码:
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配置中构建。
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- C++项目编译强制使用 /clr 选项,尽管在没有公共语言运行时支持的情况下执行它
- 暂时将C++项目(VS2015)移至Android操作系统.编译器选项?
- 是否有任何 MSBuild 命令行选项可以动态禁用 c++ 项目的代码分析?
- 用于在 Visual Studio 中为整个项目或解决方案定义带有参数的预处理器宏的选项
- 如何将cacert.pem与vs2015 curl项目一起包含,因此无需指定Cainfo curl选项
- Visual Lint?中的每个项目选项
- C++:使用 g++ 和 -m32 选项构建的 c++ 库在 Msys 下构建 wxWidgets 项目时出现 ld 不
- 如何在 eclipse makefile 项目中的编译器选项中设置 -std=c++0x
- 无法使项目,无法识别的命令行选项libc ++错误
- 将cmake构建选项导出到外部项目
- 为什么c++透视图和新项目选项在Eclipse中不可用
- 4.9.9.2项目选项不工作
- 无法使用/ CLR选项从Visual c++项目加载CLR
- 如何将code::块设置为在目标链接器选项之前链接项目链接器选项
- 可以qmake-configure Visual Studio项目中的命令行选项
- 在我的项目中使用预编译的头(clang/llvm,但也使用gcc).如何在make中部署-include选项
- 从下拉框中选择其他项目时更改选项卡小部件的 currentIndex()
- 使用 /Command 选项从命令行为 Visual Studio C++ 项目创建一个新文件
- 向Eclipse CDT Autotools项目添加链接器选项