转自:http://hi.baidu.com/qi_xian/blog/item/1971aa22da89ada24723e856.html
以下未经说明,listctrl默认view 风格为report
-------------------------------------------------------------------------------
1. CListCtrl 风格
LVS_ICON: 为每个item显示大图标
LVS_SMALLICON: 为每个item显示小图标
LVS_LIST: 显示一列带有小图标的item
LVS_REPORT: 显示item详细资料
直观的理解:windows资源管理器,"查看"标签下的"大图标,小图标,列表,详细资料
--------------------------------------------------------------------------------
2. 设置listctrl 风格及扩展风格
LONG lStyle;
lStyle = GetWindowLong(m_list.m_hWnd, GWL_STYLE);//获取当前窗口style
lStyle &= ~LVS_TYPEMASK; //清除显示方式位
lStyle |= LVS_REPORT; //设置style
SetWindowLong(m_list.m_hWnd, GWL_STYLE, lStyle);//设置style
DWORD dwStyle = m_list.GetExtendedStyle();
dwStyle |= LVS_EX_FULLROWSELECT;//选中某行使整行高亮(只适用与report风格的listctrl)
dwStyle |= LVS_EX_GRIDLINES;//网格线(只适用与report风格的listctrl)
dwStyle |= LVS_EX_CHECKBOXES;//item前生成checkbox控件
m_list.SetExtendedStyle(dwStyle); //设置扩展风格
注:listview的style请查阅msdn
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wceshellui5/html/wce50lrflistviewstyles.asp
--------------------------------------------------------------------------------
3. 插入数据
m_list.InsertColumn( 0, "ID", LVCFMT_LEFT, 40 );//插入列
m_list.InsertColumn( 1, "NAME", LVCFMT_LEFT, 50 );
//新插入的在上面
int nRow = m_list.InsertItem(0, "11");// 插入行
m_list.SetItemText(nRow, 1, "jacky");//设置其它列数据
//新插入的数据在下面
int nIndex = m_list.GetItemCount();
LV_ITEM lvItem;
lvItem.mask = LVIF_TEXT ;
lvItem.iItem = nIndex; //行数
lvItem.iSubItem = 0;
lvItem.pszText = (char*)(LPCTSTR)strCount; //第一列
//在最后一行插入记录值.
m_list.InsertItem(&lvItem);
//插入其它列
m_list.SetItemText(nIndex,1,strLat);
--------------------------------------------------------------------------------
4. 一直选中item
选中style中的Show selection always,或者在上面第2点中设置LVS_SHOWSELALWAYS
--------------------------------------------------------------------------------
5. 选中和取消选中一行
int nIndex = 0;
//选中
m_list.SetItemState(nIndex, LVIS_SELECTED|LVIS_FOCUSED, LVIS_SELECTED|LVIS_FOCUSED);
//取消选中
m_list.SetItemState(nIndex, 0, LVIS_SELECTED|LVIS_FOCUSED);
--------------------------------------------------------------------------------
6. 得到listctrl中所有行的checkbox的状态
m_list.SetExtendedStyle(LVS_EX_CHECKBOXES);
CString str;
for(int i=0; i
{
if( m_list.GetItemState(i, LVIS_SELECTED) == LVIS_SELECTED || m_list.GetCheck(i))
{
str.Format(_T("第%d行的checkbox为选中状态"), i);
AfxMessageBox(str);
}
}
--------------------------------------------------------------------------------
7. 得到listctrl中所有选中行的序号
方法一:
CString str;
for(int i=0; i
{
if( m_list.GetItemState(i, LVIS_SELECTED) == LVIS_SELECTED )
{
str.Format(_T("选中了第%d行"), i);
AfxMessageBox(str);
}
}
方法二:
POSITION pos = m_list.GetFirstSelectedItemPosition();
if (pos == NULL)
TRACE0("No items were selected!/n");
Else
{
while (pos)
{
int nItem = m_list.GetNextSelectedItem(pos);
TRACE1("Item %d was selected!/n", nItem);
// you could do your own processing on nItem here
}
}
--------------------------------------------------------------------------------
8. 得到item的信息
TCHAR szBuf[1024];
LVITEM lvi;
lvi.iItem = nItemIndex;
lvi.iSubItem = 0;
lvi.mask = LVIF_TEXT;
lvi.pszText = szBuf;
lvi.cchTextMax = 1024;
m_list.GetItem(&lvi);
关于得到设置item的状态,还可以参考msdn文章
Q173242: Use Masks to Set/Get Item States in ClistCtrl
http://support.microsoft.com/kb/173242/en-us
--------------------------------------------------------------------------------
9. 得到listctrl的所有列的header字符串内容
LVCOLUMN lvcol;
char str[256];
int nColNum;
CString strColumnName[4];//假如有4列
nColNum = 0;
lvcol.mask = LVCF_TEXT;
lvcol.pszText = str;
lvcol.cchTextMax = 256;
while(m_list.GetColumn(nColNum, &lvcol))
{
strColumnName[nColNum] = lvcol.pszText;
nColNum++;
}
--------------------------------------------------------------------------------
10. 使listctrl中一项可见,即滚动滚动条
m_list.EnsureVisible(i, FALSE);
--------------------------------------------------------------------------------
11. 得到listctrl列数
int nHeadNum = m_list.GetHeaderCtrl()->GetItemCount();
--------------------------------------------------------------------------------
12. 删除所有列
方法一:
while ( m_list.DeleteColumn (0))
因为你删除了第一列后,后面的列会依次向上移动。
方法二:
int nColumns = 4;
for (int i=nColumns-1; i>=0; i--)
m_list.DeleteColumn (i);
删除所有行
直接用第7点的方法得到所有选中的行号,然后用DeleteItem(i)想删除所有行,这样是行不通的。因为ListCtrl的行号是从上往下排列的,你删除了上面的行后,下面的行号也随之改变,所以用此方法无法删除所有行。正确的方法是从下往上删除行。如下所示:
for(int i=m_list.GetItemCount()-1; i>=0;i--)
{
if( m_list.GetItemState(i, LVIS_SELECTED) == LVIS_SELECTED )
{
m_list.DeleteItem(i);
}
}
--------------------------------------------------------------------------------
13. 得到单击的listctrl的行列号
添加listctrl控件的NM_CLICK消息相应函数
void CTest6Dlg::OnClickList1(NMHDR* pNMHDR, LRESULT* pResult)
{
// 方法一:
// 方法二:
*pResult = 0;
}
--------------------------------------------------------------------------------
14. 判断是否点击在listctrl的checkbox上
添加listctrl控件的NM_CLICK消息相应函数
void CTest6Dlg::OnClickList1(NMHDR* pNMHDR, LRESULT* pResult)
{
DWORD dwPos = GetMessagePos();
CPoint point( LOWORD(dwPos), HIWORD(dwPos) );
m_list.ScreenToClient(&point);
LVHITTESTINFO lvinfo;
lvinfo.pt = point;
lvinfo.flags = LVHT_ABOVE;
UINT nFlag;
int nItem = m_list.HitTest(point, &nFlag);
//判断是否点在checkbox上
if(nFlag == LVHT_ONITEMSTATEICON)
{
AfxMessageBox("点在listctrl的checkbox上");
}
*pResult = 0;
}
--------------------------------------------------------------------------------
15. 右键点击listctrl的item弹出菜单
添加listctrl控件的NM_RCLICK消息相应函数
void CTest6Dlg::OnRclickList1(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
if(pNMListView->iItem != -1)
{
DWORD dwPos = GetMessagePos();
CPoint point( LOWORD(dwPos), HIWORD(dwPos) );
CMenu menu;
VERIFY( menu.LoadMenu( IDR_MENU1 ) );
CMenu* popup = menu.GetSubMenu(0);
ASSERT( popup != NULL );
popup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this );
}
*pResult = 0;
}
16. item切换焦点时(包括用键盘和鼠标切换item时),状态的一些变化顺序
添加listctrl控件的LVN_ITEMCHANGED消息相应函数
void CTest6Dlg::OnItemchangedList1(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
// TODO: Add your control notification handler code here
CString sTemp;
if((pNMListView->uOldState & LVIS_FOCUSED) == LVIS_FOCUSED && (pNMListView->uNewState & LVIS_FOCUSED) == 0)
{
sTemp.Format("%d losted focus",pNMListView->iItem);
}
else if((pNMListView->uOldState & LVIS_FOCUSED) == 0 &&
(pNMListView->uNewState & LVIS_FOCUSED) == LVIS_FOCUSED)
{
sTemp.Format("%d got focus",pNMListView->iItem);
}
if((pNMListView->uOldState & LVIS_SELECTED) == LVIS_SELECTED &&
(pNMListView->uNewState & LVIS_SELECTED) == 0)
{
sTemp.Format("%d losted selected",pNMListView->iItem);
}
else if((pNMListView->uOldState & LVIS_SELECTED) == 0 && (pNMListView->uNewState & LVIS_SELECTED) == LVIS_SELECTED)
{
sTemp.Format("%d got selected",pNMListView->iItem);
}
*pResult = 0;
--------------------------------------------------------------------------------
17. 得到另一个进程里的listctrl控件的item内容
http://www.codeproject.com/threads/int64_memsteal.asp
--------------------------------------------------------------------------------
18. 选中listview中的item
Q131284: How To Select a Listview Item Programmatically
http://support.microsoft.com/kb/131284/en-us
--------------------------------------------------------------------------------
19. 如何在CListView中使用CListCtrl的派生类
http://www.codeguru.com/cpp/controls/listview/introduction/article.php/c919/
--------------------------------------------------------------------------------
20. listctrl的subitem添加图标
m_list.SetExtendedStyle(LVS_EX_SUBITEMIMAGES);
m_list.SetItem(..); //具体参数请参考msdn
21. 在CListCtrl显示文件,并根据文件类型来显示图标
网上找到的代码,share
BOOL CTest6Dlg::OnInitDialog()
{
CDialog::OnInitDialog();
HIMAGELIST himlSmall;
HIMAGELIST himlLarge;
SHFILEINFO sfi;
char cSysDir[MAX_PATH];
CString strBuf;
memset(cSysDir, 0, MAX_PATH);
GetWindowsDirectory(cSysDir, MAX_PATH);
strBuf = cSysDir;
sprintf(cSysDir, "%s", strBuf.Left(strBuf.Find("[url=file://")+1/]//")+1[/url]));
himlSmall = (HIMAGELIST)SHGetFileInfo ((LPCSTR)cSysDir, 0, &sfi, sizeof(SHFILEINFO), SHGFI_SYSICONINDEX | SHGFI_SMALLICON );
himlLarge = (HIMAGELIST)SHGetFileInfo((LPCSTR)cSysDir, 0, &sfi, s izeof(SHFILEINFO), SHGFI_SYSICONINDEX | SHGFI_LARGEICON);
if (himlSmall && himlLarge)
{
::SendMessage(m_list.m_hWnd,LVM_SETIMAGELIST, (WPARAM)LVSIL_SMALL, (LPARAM)himlSmall);
::SendMessage(m_list.m_hWnd, LVM_SETIMAGELIST,
(WPARAM)LVSIL_NORMAL, (LPARAM)himlLarge);
}
return TRUE; // return TRUE unless you set the focus to a control
}
void CTest6Dlg::AddFiles(LPCTSTR lpszFileName, BOOL bAddToDocument)
{
int nIcon = GetIconIndex(lpszFileName, FALSE, FALSE);
CString strSize;
CFileFind filefind;
// get file size
if (filefind.FindFile(lpszFileName))
{
filefind.FindNextFile();
strSize.Format("%d", filefind.GetLength());
}
else
strSize = "0";
// split path and filename
CString strFileName = lpszFileName;
CString strPath;
int nPos = strFileName.ReverseFind('//');
if (nPos != -1)
{
strPath = strFileName.Left(nPos);
strFileName = strFileName.Mid(nPos + 1);
}
// insert to list
int nItem = m_list.GetItemCount();
m_list.InsertItem(nItem, strFileName, nIcon);
m_list.SetItemText(nItem, 1, strSize);
m_list.SetItemText(nItem, 2, strFileName.Right(3));
m_list.SetItemText(nItem, 3, strPath);
}
int CTest6Dlg::GetIconIndex(LPCTSTR lpszPath, BOOL bIsDir, BOOL bSelected)
{
SHFILEINFO sfi;
memset(&sfi, 0, sizeof(sfi));
if (bIsDir)
{
SHGetFileInfo(lpszPath,
FILE_ATTRIBUTE_DIRECTORY,
&sfi,
sizeof(sfi),
SHGFI_SMALLICON | SHGFI_SYSICONINDEX |
SHGFI_USEFILEATTRIBUTES |(bSelected ? SHGFI_OPENICON : 0));
return sfi.iIcon;
}
else
{
SHGetFileInfo (lpszPath,
FILE_ATTRIBUTE_NORMAL,
&sfi,
sizeof(sfi),
SHGFI_SMALLICON | SHGFI_SYSICONINDEX |
SHGFI_USEFILEATTRIBUTES | (bSelected ? SHGFI_OPENICON : 0));
return sfi.iIcon;
}
return -1;
}
--------------------------------------------------------------------------------
22. listctrl内容进行大数据量更新时,避免闪烁
m_list.SetRedraw(FALSE);
//更新内容
m_list.SetRedraw(TRUE);
m_list.Invalidate();
m_list.UpdateWindow();
或者参考
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_mfc_cwnd.3a3a.setredraw.asp
--------------------------------------------------------------------------------
23. listctrl排序
Q250614:How To Sort Items in a CListCtrl in Report View
http://support.microsoft.com/kb/250614/en-us
--------------------------------------------------------------------------------
24. 在listctrl中选中某个item时动态改变其icon或bitmap
Q141834: How to change the icon or the bitmap of a CListCtrl item in Visual C++
http://support.microsoft.com/kb/141834/en-us
--------------------------------------------------------------------------------
25. 在添加item后,再InsertColumn()后导致整列数据移动的问题
Q151897: CListCtrl::InsertColumn() Causes Column Data to Shift
http://support.microsoft.com/kb/151897/en-us
--------------------------------------------------------------------------------
26. 关于listctrl第一列始终居左的问题
解决办法:把第一列当一个虚列,从第二列开始插入列及数据,最后删除第一列。
具体解释参阅http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/commctls/listview/structures/lvcolumn.asp
--------------------------------------------------------------------------------
27. 锁定column header的拖动
http://msdn.microsoft.com/msdnmag/issues/03/06/CQA/
--------------------------------------------------------------------------------
28. 如何隐藏clistctrl的列
把需隐藏的列的宽度设为0,然后检测当该列为隐藏列时,用上面第27点的锁定column 的拖动来实现
--------------------------------------------------------------------------------
29. listctrl进行大数据量操作时,使用virtual list
http://www.codeguru.com/cpp/controls/listview/advanced/article.php/c4151/
http://www.codeproject.com/listctrl/virtuallist.asp
--------------------------------------------------------------------------------
30. 关于item只能显示259个字符的问题
解决办法:需要在item上放一个edit。
--------------------------------------------------------------------------------
31. 响应在listctrl的column header上的鼠标右键单击
Q125694: How To Find Out Which Listview Column Was Right-Clicked
http://support.microsoft.com/kb/125694/en-us
--------------------------------------------------------------------------------
32. 类似于windows资源管理器的listview
Q234310: How to implement a ListView control that is similar to Windows Explorer by using DirLV.exe
http://support.microsoft.com/kb/234310/en-us
--------------------------------------------------------------------------------
33. 在ListCtrl中OnTimer只响应两次的问题
Q200054:
PRB:onTimer() Is Not Called Repeatedly for a List Control
http://support.microsoft.com/kb/200054/en-us
--------------------------------------------------------------------------------
34. 以下为一些为实现各种自定义功能的listctrl派生类
(1) 拖放
http://www.codeproject.com/listctrl/dragtest.asp
在CListCtrl和CTreeCtrl间拖放
http://support.microsoft.com/kb/148738/en-us
(2) 多功能listctrl
支持subitem可编辑,图标,radiobutton,checkbox,字符串改变颜色的类
http://www.codeproject.com/listctrl/quicklist.asp
支持排序,subitem可编辑,subitem图标,subitem改变颜色的类
http://www.codeproject.com/listctrl/ReportControl.asp
(3) subitem中显示超链接
http://www.codeproject.com/listctrl/CListCtrlLink.asp
(4) subitem的tooltip提示
http://www.codeproject.com/listctrl/ctooltiplistctrl.asp
(5) subitem中显示进度条
http://www.codeproject.com/listctrl/ProgressListControl.asp
http://www.codeproject.com/listctrl/napster.asp
http://www.codeguru.com/Cpp/controls/listview/article.php/c4187/
(6) 动态改变subitem的颜色和背景色
http://www.codeproject.com/listctrl/highlightlistctrl.asp
http://www.codeguru.com/Cpp/controls/listbox/colorlistboxes/article.php/c4757/
(7) 类vb属性对话框
http://www.codeproject.com/listctrl/propertylistctrl.asp
http://www.codeguru.com/Cpp/controls/listview/propertylists/article.php/c995/
http://www.codeguru.com/Cpp/controls/listview/propertylists/article.php/c1041/
(8) 选中subitem(只高亮选中的item)
http://www.codeproject.com/listctrl/SubItemSel.asp
http://www.codeproject.com/listctrl/ListSubItSel.asp
(9) 改变行高
http://www.codeproject.com/listctrl/changerowheight.asp
(10) 改变行颜色
http://www.codeproject.com/listctrl/coloredlistctrl.asp
(11) 可编辑subitem的listctrl
http://www.codeproject.com/listctrl/nirs2000.asp
http://www.codeproject.com/listctrl/editing_subitems_in_listcontrol.asp
(12) subitem可编辑,插入combobox,改变行颜色,subitem的tooltip提示
http://www.codeproject.com/listctrl/reusablelistcontrol.asp
(13) header 中允许多行字符串
http://www.codeproject.com/listctrl/headerctrlex.asp
(14) 插入combobox
http://www.codeguru.com/Cpp/controls/listview/editingitemsandsubitem/article.php/c979/
(15) 添加背景图片
http://www.codeguru.com/Cpp/controls/listview/backgroundcolorandimage/article.php/c4173/
http://www.codeguru.com/Cpp/controls/listview/backgroundcolorandimage/article.php/c983/
http://www.vchelp.net/vchelp/archive.asp?type_id=9&class_id=1&cata_id=1&article_id=1088&search_term=
(16) 自适应宽度的listctrl
http://www.codeproject.com/useritems/AutosizeListCtrl.asp
(17) 改变ListCtrl高亮时的颜色(默认为蓝色)
处理NM_CUSTOMDRAW
http://www.codeproject.com/listctrl/lvcustomdraw.asp
//--------------------------------------------------------------------------------------------------------
开发环境:visual studio 2008 sp1
1、新建一个基于对话框的MFC应用程序。在对话框上拖放一个listcontrol控件和一个button控件,给listcontrol控件添加一个名为m_StoreItems的变量。添加button的点击响应函数。
void CDepartmentStoreDlg::OnBnClickedNewitem()
{
// TODO: 在此添加控件通知处理程序代码
srand((unsigned)time(NULL));
TCHAR strNumber[20];//这里不要定义为char或者CString类型,不然后面 lvItem.pszText会报错。
int number1 = rand() % 100;
int number2 = rand() % 100;
wsprintf(strNumber,_T("%d-%d"), number1, number2);
LVITEM lvItem;
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 0;
lvItem.iSubItem = 0;
lvItem.pszText = strNumber;
m_StoreItems.InsertItem(&lvItem);
}
运行效果如下,效果相当于listbox控件,就是一个列表,一行一行的:
现在设置为报表视图,显示成表格形式。
在初始化函数里添加:
BOOL CDepartmentStoreDlg::OnInitDialog()
{
CDialog::OnInitDialog();
m_StoreItems.SetView(LVS_REPORT);//如果在属性里面设置了listview的view是report,这里就没必要了,默认的是icon
LVCOLUMN lvColumn;
lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH; //掩码设置了fmt值、显示列标题和指定宽度
lvColumn.fmt = LVCFMT_LEFT; //设置作对其模式
lvColumn.cx = 120; //设置标题的宽度为120个像素
lvColumn.pszText = _T("Full Name"); //设置标题(列名)
m_StoreItems.InsertColumn(0, &lvColumn); //添加列,索引为0
lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH;
lvColumn.fmt = LVCFMT_LEFT;
lvColumn.cx = 100;
lvColumn.pszText = _T("Profession");
m_StoreItems.InsertColumn(1, &lvColumn);
lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH;
lvColumn.fmt = LVCFMT_LEFT;
lvColumn.cx = 80;
lvColumn.pszText = _T("Fav Sport");
m_StoreItems.InsertColumn(2, &lvColumn);
lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH;
lvColumn.fmt = LVCFMT_LEFT;
lvColumn.cx = 75;
lvColumn.pszText = _T("Hobby");
m_StoreItems.InsertColumn(3, &lvColumn);
}
下面给报表添加点实际的内容。
继续在初始化函数里添加:
LVITEM lvItem;
int nItem;
lvItem.mask = LVIF_TEXT;//这里的掩码设置一定要注意,因为item和column的掩码值很像,例如LVIF_TEXT和LVCF_TEXT,I对应的item,C对应的column,不然的话会显示不出来的,这个地方害死我了,因为有插件自动补全代码,补全后没注意看,结果没有对应,郁闷了好一会
lvItem.iItem = 0;//行号(索引,从0开始),报表相当于二维数组的模式,添加行内容时要指定行号和列号
lvItem.iSubItem = 0;//列号(索引,从0开始)
lvItem.pszText = _T("Sandra C. Anschwitz");//内容
nItem = m_StoreItems.InsertItem(&lvItem);//插入这一行,返回行号(索引)
m_StoreItems.SetItemText(nItem, 1, _T("Singer"));//设置行索引(行号)和列索引(列号)的值
m_StoreItems.SetItemText(nItem, 2, _T("HandBall"));
m_StoreItems.SetItemText(nItem, 3, _T("Beach"));
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 1;
lvItem.iSubItem = 0;
lvItem.pszText = _T("Roger A. Miller");
nItem = m_StoreItems.InsertItem(&lvItem);
m_StoreItems.SetItemText(nItem, 1, _T("Footballer"));
m_StoreItems.SetItemText(nItem, 2, _T("Tennis"));
m_StoreItems.SetItemText(nItem, 3, _T("Teaching"));
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 2;
lvItem.iSubItem = 0;
lvItem.pszText = _T("Marie-Julie W. Gross");
nItem = m_StoreItems.InsertItem(&lvItem);
m_StoreItems.SetItemText(nItem, 1, _T("Student"));
m_StoreItems.SetItemText(nItem, 2, _T("Boxing"));
m_StoreItems.SetItemText(nItem, 3, _T("Programming"));
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 3;
lvItem.iSubItem = 0;
lvItem.pszText = _T("Ella Pius Roger");
nItem = m_StoreItems.InsertItem(&lvItem);
m_StoreItems.SetItemText(nItem, 1, _T("Architect"));
m_StoreItems.SetItemText(nItem, 2, _T("Ping-Pong"));
m_StoreItems.SetItemText(nItem, 3, _T("Songo"));
中途小结:
在报表视图中,要做的主要有下面几步:
1)确保当前视图为报表视图,在属性窗口设置view或者在代码中设置为view模式
2)添加列:用到的数据结构是LVCOLUMN (就是list view column,对应的掩码也是LVCF_,list view column format)
3)添加行:用到的数据结构是LVITEM (list view item,对应的掩码是LVIF_,list view item format)
添加行的时候先添加第一个元素,即行索引为nItem,列索引为0,然后InsertItem,返回当前行的索引,之后就是设置该行的其他元素了,指定行、列索引和设置值即可。
4)删除行:BOOL DeleteItem(int nItem);删除指定的索引为nItem的行内容。有时候我们会先选中某行,然后删除,这个时候需要用到函数int GetNextItem(int nItem, int nFlags);从指定的索引nItem(不包括该索引,如果要包括该行的话,设置nItem -1即可)开始寻找满足nFlags条件的Item,成功则返回找到的Item的索引(如果有多个,则返回第一个),失败返回-1.这样的话如果要删除选中的某行,则可以这样实现 m_StoreItems.DeleteItem(m_StoreItems.GetNextItem(-1,LVNI_SELECTED));(建议设置扩展风格时,把整行选中设置进来this->m_StoreItems.SetExtendedStyle( LVS_EX_FULLROWSELECT);这样选中的时候就是一行了,否则会是一格)。如果要删除多行选中的,则可以用下面的代码:
int nIndex;
do
{
nIndex = m_StoreItems.GetNextItem(-1,LVNI_SELECTED);
m_StoreItems.DeleteItem(nIndex);
} while (nIndex != -1);
这里添加一点调整列宽的,以下代码可供参考(摘自CSDN):
voidCMyListView::AutoAdjustColumnWidth()
{
CHeaderCtrl*pHeaderCtrl=m_pListCtrl->GetHeaderCtrl();
m_pListCtrl->SetRedraw(FALSE);//防止闪烁
pHeaderCtrl->SetRedraw(FALSE);//防止闪烁
intnColumnCount=pHeaderCtrl->GetItemCount(); //获取列数
for(inti=0; i<nColumnCount; i++)
{
m_pListCtrl->SetColumnWidth(i, LVSCW_AUTOSIZE);
intnColumnWidth=m_pListCtrl->GetColumnWidth(i);
m_pListCtrl->SetColumnWidth(i, LVSCW_AUTOSIZE_USEHEADER);
intnHeaderWidth=m_pListCtrl->GetColumnWidth(i);
m_pListCtrl->SetColumnWidth(i, max(nColumnWidth, nHeaderWidth)+10);
}
pHeaderCtrl->SetRedraw(TRUE);//此处开启刷新,避免闪烁
m_pListCtrl->SetRedraw(TRUE);
pHeaderCtrl->Invalidate();//Update Window to redraw.
pHeaderCtrl->UpdateWindow();
}
下面就开始设置图片了。
新建两个bitmap资源,大小为16*16,ID分别为IDB_UP和IDB_LOSANGE,初始化函数CDepartmentStoreDlg::OnInitDialog()改为如下:
m_StoreItems.SetView(LVS_REPORT);
LVCOLUMN lvColumn;
CBitmap bmpUP, bmpLosange;
bmpUP.LoadBitmap(IDB_UP);
bmpLosange.LoadBitmap(IDB_LOSANGE);
CImageList *ImgHeaders = new CImageList();
ImgHeaders->Create(16, 16, ILC_MASK, 1, 1);
ImgHeaders->Add(&bmpUP, RGB(0, 0, 0));
ImgHeaders->Add(&bmpLosange, RGB(0, 0, 0));
m_StoreItems.SetImageList(ImgHeaders, LVSIL_SMALL);
lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH | LVCF_IMAGE;
lvColumn.fmt = LVCFMT_LEFT | LVCFMT_IMAGE;
lvColumn.cx = 120;
lvColumn.pszText = _T("Full Name");
lvColumn.iImage = 0;
m_StoreItems.InsertColumn(0, &lvColumn);
lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH;
lvColumn.fmt = LVCFMT_LEFT;
lvColumn.cx = 100;
lvColumn.pszText = _T("Profession");
m_StoreItems.InsertColumn(1, &lvColumn);
lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH | LVCF_IMAGE;
lvColumn.fmt = LVCFMT_LEFT | LVCFMT_IMAGE;
lvColumn.iImage = 1;
lvColumn.cx = 80;
lvColumn.pszText = _T("Fav Sport");
m_StoreItems.InsertColumn(2, &lvColumn);
lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH;
lvColumn.fmt = LVCFMT_LEFT;
lvColumn.cx = 75;
lvColumn.pszText = _T("Hobby");
m_StoreItems.InsertColumn(3, &lvColumn);
继续完善。给CDepartmentStoreDlg类添加变量:
CImageList m_SmallImg;
CImageList m_LargeImg;
函数:
DWORD GetViewType(void);
void SetViewType(DWORD dwViewType);
cpp中的实现:
DWORD CDepartmentStoreDlg::GetViewType(void)
{
return (GetStyle() & LVS_TYPEMASK);
}
void CDepartmentStoreDlg::SetViewType(DWORD dwViewType)
{
DWORD dwCurType;
HWND hWnd;
hWnd = this->m_StoreItems;
GetSafeHwnd();
dwCurType = ::GetWindowLong(hWnd, GWL_STYLE);
dwCurType &= ~LVS_TYPEMASK;
dwViewType |= dwCurType;
::SetWindowLong(hWnd, GWL_STYLE, dwViewType);
}
窗体上添加Large、Small、List、Details四个button,添加鼠标点击事件的响应函数,如下:
void CDepartmentStoreDlg::OnBnClickedLarge()
{
// TODO: 在此添加控件通知处理程序代码
SetViewType(LVS_ICON);
}
void CDepartmentStoreDlg::OnBnClickedSmall()
{
// TODO: 在此添加控件通知处理程序代码
if( GetViewType() != LVS_SMALLICON)
SetViewType(LVS_SMALLICON);
}
void CDepartmentStoreDlg::OnBnClickedDetail()
{
// TODO: 在此添加控件通知处理程序代码
if( GetViewType() != LVS_REPORT)
SetViewType(LVS_REPORT);
}
void CDepartmentStoreDlg::OnBnClickedList()
{
// TODO: 在此添加控件通知处理程序代码
if( GetViewType() != LVS_LIST)
SetViewType(LVS_LIST);
}
窗体上的New Item按钮调用的窗体如下,用来添加数据, 给窗体创建类,并给控件添加相应变量。
添加2个位图资源,属性为ID:IDB_Larging Weight:162 Height:32,ID:IDB_Smalling Weight:80 Height:16
初始化函数代码:
m_StoreItems.SetView(LVS_REPORT);
LVCOLUMN lvColumn;
lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH;
lvColumn.fmt = LVCFMT_CENTER;
lvColumn.cx = 60;
lvColumn.pszText = _T("Item #");
this->m_StoreItems.InsertColumn(0, &lvColumn);
lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH;
lvColumn.fmt = LVCFMT_LEFT;
lvColumn.cx = 100;
lvColumn.pszText = _T("Category");
this->m_StoreItems.InsertColumn(1, &lvColumn);
lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH;
lvColumn.fmt = LVCFMT_LEFT;
lvColumn.cx = 160;
lvColumn.pszText = _T("Item Name");
this->m_StoreItems.InsertColumn(2, &lvColumn);
lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH;
lvColumn.fmt = LVCFMT_LEFT;
lvColumn.cx = 80;
lvColumn.pszText = _T("Size");
this->m_StoreItems.InsertColumn(3, &lvColumn);
lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH;
lvColumn.fmt = LVCFMT_RIGHT;
lvColumn.cx = 60;
lvColumn.pszText = _T("Unit Price");
this->m_StoreItems.InsertColumn(4, &lvColumn);
lvColumn.mask = LVCF_FMT | LVCF_TEXT | LVCF_WIDTH;
lvColumn.fmt = LVCFMT_RIGHT;
lvColumn.cx = 30;
lvColumn.pszText = _T("Qty");
this->m_StoreItems.InsertColumn(5, &lvColumn);
this->m_StoreItems.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES);//设置扩展风格
m_SmallImg.Create(IDB_Smalling, 16, 1, RGB(255, 255, 255));
m_LargeImg.Create(IDB_Larging, 32, 1, RGB(255, 255, 245));
m_StoreItems.SetImageList(&m_SmallImg, LVSIL_SMALL);
m_StoreItems.SetImageList(&m_LargeImg, LVSIL_NORMAL);
New Item按钮的响应函数为(将添加item的类include进来):
void CDepartmentStoreDlg::OnBnClickedNewitem()
{
// TODO: 在此添加控件通知处理程序代码
CNewItemDlg dlg;//这个是添加新数据的窗体类
srand((unsigned)time(NULL));
TCHAR strNumber[20];
int number1 = rand() % 100;
int number2 = rand() % 100;
wsprintf(strNumber,_T("%d-%d"), number1, number2);
dlg.m_ItemNumber = strNumber;
if (dlg.DoModal())
{
LVITEM lvItem;
int nItem;
int imgNbr;
if( dlg.m_Category == "Babies" )
imgNbr = 0;
else if( dlg.m_Category == "Teens" )
imgNbr = 1;
else if( dlg.m_Category == "Women" )
imgNbr = 2;
else if( dlg.m_Category == "Men" )
imgNbr = 3;
else
imgNbr = 4;
lvItem.mask = LVIF_IMAGE | LVIF_TEXT;
lvItem.iItem = 0;
lvItem.iSubItem = 0;
lvItem.pszText = strNumber;
lvItem.iImage = imgNbr;
nItem = this->m_StoreItems.InsertItem(&lvItem);
this->m_StoreItems.SetItemText(nItem, 1, dlg.m_Category);
this->m_StoreItems.SetItemText(nItem, 2, dlg.m_ItemName);
this->m_StoreItems.SetItemText(nItem, 3, dlg.m_ItemSize);
this->m_StoreItems.SetItemText(nItem, 4, dlg.m_UnitPrice);
this->m_StoreItems.SetItemText(nItem, 5, dlg.m_Quantity);
}
}
效果图:
this->m_StoreItems.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVS_EX_CHECKBOXES);//新加checkbox风格
源码下载:http://download.csdn.net/source/2940438