目录
列表框(ListBox) - CListBox
基本概念
成员方法
示例代码
列表框控件是一个窗口,通常在对话框中使用,用于显示一个项目列表,用户可以从中选择一个或多个项目。
列表框可以设置为单选(一次只能选择一个项目)或多选(可以同时选择多个项目)。
在MFC中,列表框控件由 CListBox 类管理。这个类提供了操作列表框的方法和属性。
Create:创建列表框控件并将其附加到 CListBox 对象。
AddString:向列表框中添加一个字符串。
DeleteString:从列表框中删除一个字符串。
InsertString:在列表框中的指定位置插入一个字符串。
ResetContent:清除列表框中的所有字符串。
GetCount:获取列表框中字符串的数量。
GetCurSel:获取列表框中当前选中项的索引(单选模式)。
SetCurSel:设置列表框中当前选中的字符串。
GetSel:获取列表框中指定项的选中状态。
SetSel:设置列表框中指定项的选中状态(多选模式)。
GetText:从列表框中获取指定项的文本。
GetTextLen:获取列表框中指定项的文本长度。
void CMainDlg::OnBnClickedButton4() { CString strListItem; m_ListItem.GetWindowTextW(strListItem); m_ListBox.AddString(strListItem); } void CMainDlg::OnBnClickedButton5() { int nIndex = m_ListBox.GetCurSel(); if (nIndex != LB_ERR) { m_ListBox.DeleteString(nIndex); } } void CMainDlg::OnBnClickedButton6() { int nIndex = m_ListBox.GetCurSel(); if (nIndex != LB_ERR) { CString strListItem; m_ListItem.GetWindowTextW(strListItem); m_ListBox.InsertString(nIndex, strListItem); } } void CMainDlg::OnBnClickedButton15() { m_ListBox.ResetContent(); } void CMainDlg::OnBnClickedButton16() { m_ListBox.SetCurSel(0); } void CMainDlg::OnBnClickedButton17() { int nIndex = m_ListBox.GetCurSel(); if (nIndex != LB_ERR) { CString strItemText; m_ListBox.GetText(nIndex, strItemText); AfxMessageBox(strItemText); } } void CMainDlg::OnLbnDblclkList1() { int nIndex = m_ListBox.GetCurSel(); if (nIndex != LB_ERR) { CString strItemText; m_ListBox.GetText(nIndex, strItemText); AfxMessageBox(strItemText); } }