List-View 排序方案一
最近需要解决List-View排序的问题,网上很多资料, 却很少有说明使用条件的,所以程序调试出问题,查阅MSDN, 有些心得,分享一下。
此排序方案适用条件:
仅使用于Common List-View, 而不支持Virtual List-View(或许需改进),即不支持Owner Data(窗口风格不支持LVS_OWNERDATA), 支持该风格的待续。
代码(部分来源于网络)。
struct DictListData
{
CListCtrl * plistctrl;
int isub;
int iseq;
};
BEGIN_MESSAGE_MAP()
ON_NOTIFY(LVN_COLUMNCLICK, IDC_LIST, OnColumnclickList)
END_MESSAGE_MAP()
static int CALLBACK CompareFunc(LPARAM lParam1,LPARAM lParam2,LPARAM lParamSort)
{
DictListData * pListData = (DictListData *)lParamSort;
CListCtrl * pDictlistCtrl = pListData->plistctrl;
int isub = pListData->isub;
LVFINDINFO findInfo;
findInfo.flags = LVFI_PARAM;
findInfo.lParam = lParam1;
int iItem1 = pDictlistCtrl->FindItem(&findInfo, -1);
findInfo.lParam = lParam2;
int iItem2 = pDictlistCtrl->FindItem(&findInfo, -1);
CString strItem1 = pDictlistCtrl->GetItemText(iItem1,isub);
CString strItem2 = pDictlistCtrl->GetItemText(iItem2,isub);
if(pListData->iseq)
{
return strcmp(strItem2, strItem1);
}
else
{
return -strcmp(strItem2, strItem1);
}
}
void CXXXDlg::OnColumnclickList1(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_LISTVIEW * pNMListView = (NM_LISTVIEW * )pNMHDR;
// TODO: Add your control notification handler code here
DictListData *tmpp = new DictListData;
tmpp->plistctrl = &m_List; //Your list need to be sorted
tmpp->isub = pNMListView->iSubItem;
int sortnum = (int)GetProp(m_List.GetSafeHwnd(),"SORT_COLUMN");
int sortasc = (int)GetProp(m_List.GetSafeHwnd(),"SORT_DIRECTION");
if(sortnum == pNMListView->iSubItem)
{
sortasc = (sortasc + 1) % 2;
SetProp(m_List.GetSafeHwnd(),"SORT_DIRECTION",(HANDLE)sortasc);
}
SetProp(m_List.GetSafeHwnd(),"SORT_COLUMN",(HANDLE)pNMListView->iSubItem);
tmpp->iseq = sortasc;
m_List.SortItems(CompareFunc,(LPARAM)tmpp);
for (UINT i = 0; i < m_ExistingList.size(); i++) // The enter point
{
m_List.SetItemData(i,i);
}
*pResult = 0;
}