标签:
源代码及可执行文件下载地址: http://files.cnblogs.com/rainboy2010/CSortListCtrl_Demo.zip
界面设计中我们经常会用到ListCtrl控件,那么问题来了,如何实现ListCtrl排序呢?在这里提供一个CListCtrl的继承类CSortListCtrl类,支持某一列按照字符串,十进制或十六进制排序,默认按照字符串方式进行排序。
enum ITEM_COMPARE_TYPE { /// String comparison. ICT_STRING, /// Integer comparison. ICT_INTEGER, /// Hexadecimal comparison. ICT_HEXADECIMAL };
首先需要添加点击列表头的响应函数
void CSortListCtrl::OnLvnColumnclick(NMHDR *pNMHDR, LRESULT *pResult) { LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR); int iColumnNumber=pNMLV->iSubItem; _ASSERTE(iColumnNumber >= 0); if (m_iColumnNumber == iColumnNumber) { m_bAscending = ! m_bAscending; SetSortImage(m_bAscending?0:1); } else { if(m_iColumnNumber>=0) { SetSortImage(-1); } m_iColumnNumber=iColumnNumber; m_bAscending=TRUE; SetSortImage(0); } LISTVIEW_SORT_PARAMS lvSortParams; lvSortParams.hwndList=m_hWnd; lvSortParams.iColumnNumber=iColumnNumber; lvSortParams.eCompareType=GetSortType(iColumnNumber); lvSortParams.bAscending=m_bAscending; SortItemsEx(&ListViewCompareFunc,(DWORD_PTR)&lvSortParams); *pResult = 0; }
然后实现ListCtrl的排序函数
排序函数的形式为: int CALLBACK CompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
当在OnLvnColumnclick中使用SortItems或SortItemsEx时,此时参数lParam1,lParam2,lParamSort所对应的意义有所不同,具体含义可参考MSDN解释
int CALLBACK CSortListCtrl::ListViewCompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) { LISTVIEW_SORT_PARAMS* plvSortParams=( LISTVIEW_SORT_PARAMS*)lParamSort; TCHAR szItemText1[MAX_PATH]={0}; TCHAR szItemText2[MAX_PATH]={0}; ListView_GetItemText(plvSortParams->hwndList,lParam1,plvSortParams->iColumnNumber,szItemText1,MAX_PATH); ListView_GetItemText(plvSortParams->hwndList,lParam2,plvSortParams->iColumnNumber,szItemText2,MAX_PATH); int iResult; switch(plvSortParams->eCompareType) { case ICT_STRING: iResult=_tcscmp(szItemText1,szItemText2); break; case ICT_INTEGER: { int iItemValue1 = _ttoi(szItemText1); int iItemValue2 = _ttoi(szItemText2); iResult=Comparetor(iItemValue1,iItemValue2); } break; case ICT_HEXADECIMAL: { unsigned uItemValue1 = _tcstoul(szItemText1, NULL, 16); unsigned uItemValue2 = _tcstoul(szItemText2, NULL, 16); iResult = Comparetor(uItemValue1, uItemValue2); } break; default: iResult = 0; break; } return (plvSortParams->bAscending?iResult:-iResult); }
标签:
原文地址:http://www.cnblogs.com/rainboy2010/p/4315813.html