组合框、列表框
组合框的封装类:CComboBox
列表框的封装类:CListBox
一、创建名为ComboAndList的MFC工程,按照下图添加组件
修改static text Caption属性为组合框和列表框,combo box ID为IDC_COMBO,并添加控件变量m_combo、list box ID为IDC_LIST1并添加控件变量m_list
edit control ID为IDC_EDIT_INPUT,添加button ID为 IDC_BUTTON_ADD、删除button ID为IDC_BUTTON_DEL
sort用来对combo的内容排序,默认为排序,若无需排序修改此处,同理listbox排序属性也是修改此处
二、双击添加button,进入ComboAndListDlg.cpp
void CComboAndListDlg::OnBnClickedBtnAdd() { // TODO: 在此添加控件通知处理程序代码 CString strText; GetDlgItemText(IDC_EDIT_TEXT, strText); //获取文本框内容 m_cmb_demo.AddString(strText); //添加到组合框 m_cmb_demo.SetCurSel(m_cmb_demo.GetCount()-1);//选中当前添加 m_lst_demo.AddString(strText); //添加到列表框 m_lst_demo.SetCurSel(m_lst_demo.GetCount()-1); }
双击删除所选button,进入ComboAndListDlg.cpp添加
void CComboAndListDlg::OnBnClickedBtnDelete() { // TODO: 在此添加控件通知处理程序代码 int nIndex; nIndex = m_cmb_demo.GetCurSel(); if(nIndex > -1) { m_cmb_demo.DeleteString(nIndex); //删除当前选中的 if(nIndex < m_cmb_demo.GetCount()) m_cmb_demo.SetCurSel(nIndex); //删除一个,选中下一个 else m_cmb_demo.SetCurSel(0); } nIndex =m_lst_demo.GetCurSel(); if(nIndex > -1) { m_lst_demo.DeleteString(nIndex); if(nIndex < m_lst_demo.GetCount()) m_lst_demo.SetCurSel(nIndex); else m_lst_demo.SetCurSel(0); } }
三 、源码
链接:https://pan.baidu.com/s/1rSf9ylwANp5_x26atk1IPg
提取码:ydsj