欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

《实用VC编程之玩转控件》第7课:ListBox 列表控件

发布时间:2024/3/7 编程问答 54 豆豆
生活随笔 收集整理的这篇文章主要介绍了 《实用VC编程之玩转控件》第7课:ListBox 列表控件 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

本文转载自 VC驿站:

https://www.cctry.com/thread-297429-1-1.html

1、向列表框控件添加数据:
a、向列表框的结尾添加数据:

m_ListBox.AddString(_T("1"));
m_ListBox.AddString(_T("2"));
m_ListBox.AddString(_T("10"));
m_ListBox.AddString(_T("20"));

跟下拉框控件一样,添加完成后,数据的顺序并不是我们添加时候的顺序,调整下控件的 Sort 自动排序属性就可以了。

b、自定义位置插入数据:

m_ListBox.InsertString(0, _T("1"));
m_ListBox.InsertString(1, _T("2"));
m_ListBox.InsertString(2, _T("10"));
m_ListBox.InsertString(1, _T("20"));

这种插入方式不受 Sort 属性的影响,但是需要提供插入的索引位置。

2、获得列表框中总共有多少条目:

int nCount = m_ListBox.GetCount();

3、从列表框删除数据:

m_ListBox.DeleteString(0);    //删除指定索引的数据
m_ListBox.ResetContent();    //删除全部数据

4、设置列表框选中某条数据:

m_ListBox.SetCurSel(1);

参数传递要设置的索引序号,如果不想选中任何一条,那么就传递 -1.

5、获得列表框当前选中的是哪条数据:

int idx =m_ListBox.GetCurSel();

返回以0开始的选中的数据索引,如果没选中任何一条数据,则返回 -1.

6、列表框的多选模式:
刚才给大家讲解的 SetCurSel 和 GetCurSel 都是针对列表框的单选模式进行的,大家在使用其他软件的时候也注意过有的列表框控件是支持多选的,还支持 Ctrl、Shift 键快捷操作,那么应该怎么做呢?
答案是:控件的 Selection 属性进行修改。默认是 Single,也就是单选。我们可以改成 Multiple、Extended,都是多选的意思。其中 Extended 支持 Ctrl、Shift 键操作。None:选中item,但是不高亮,只显示该item上交点(item外有矩形框)。

a、多选模式下的选中操作:

    m_ListBox.SetSel(0);
    m_ListBox.SetSel(1);

b、多选模式下的获取选中操作:

int sel_count = m_ListBox.GetSelCount();
int* pSel = new int[sel_count];
m_ListBox.GetSelItems(sel_count, pSel);
for (int idx = 0; idx < sel_count; ++idx)
{
    int sel_idx = pSel[idx];
    //其他操作
}

delete[] pSel;

7、获得指定索引的字符串内容:
a、MFC的CString方式:

CString strText;
m_ListBox.GetText(sel_idx, strText);

b、非CString方式:

int text_len = m_ListBox.GetTextLen(sel_idx);
TCHAR* pszText = new TCHAR[text_len + 1];
memset(pszText, 0, sizeof(TCHAR)*text_len);
m_ListBox.GetText(sel_idx, pszText);
delete[] pszText;


8、开源控件类:
https://www.codeproject.com/Arti ... Box-derived-control
 

https://www.codeproject.com/Arti ... -List-based-Listbox
 

https://www.codeproject.com/Articles/12773/CFontListBox
 

https://www.codeproject.com/Arti ... -CListBox-Version-2
 

https://www.codeproject.com/Arti ... -Multi-line-ListBox
 

https://www.codeproject.com/Arti ... xColorPickerST-v1-1
 

https://www.codeproject.com/Arti ... dio-Buttons-MFC-ver
 

https://www.codeproject.com/Arti ... le-ListBox-Tutorial
 

https://www.codeproject.com/Arti ... ting-check-state-no
 

https://www.codeproject.com/Arti ... ith-ToolTip-Support
 

https://www.codeproject.com/Arti ... ith-selectable-text
 

https://www.codeproject.com/Articles/11359/Transparent-ListBox
 

https://www.codeproject.com/Arti ... t-Ownerdraw-Listbox
 

具体操作细节见视频教程的演示和讲解!

第7课免费试看,下载地址:

https://www.cctry.com/thread-297429-1-1.html

总结

以上是生活随笔为你收集整理的《实用VC编程之玩转控件》第7课:ListBox 列表控件的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。