1. CCZLogAnalysisDlg类外面添加如下代码:
typedef struct tag_ListSortNode
{
CListCtrl* pList;
int nOrder;
int nColum;
}LISTSORTNODE,*PLISTSORTNODE;
2. CCZLogAnalysisDlg.h头部文件添加如下代码:
//CListCtrl控件LVN_COLUMNCLICK函数的声明:
afx_msg void OnLvnColumnclickListdatainfo(NMHDR *pNMHDR, LRESULT *pResult);
//回调函数的声明:
static int CALLBACK CompareFunc(LPARAM lParam1,LPARAM lParam2,LPARAM lParamSort);
//结构体的声明:
LISTSORTNODE m_tSortColumns[3];
3. CCZLogAnalysisDlg.cpp源文件添加如下代码:
void CCZLogAnalysisDlg::OnLvnColumnclickListdatainfo(NMHDR *pNMHDR, LRESULT *pResult)
{
//LPNMLISTVIEW pNMLV = reinterpret_cast(pNMHDR);
//// TODO: 在此添加控件通知处理程序代码
//*pResult = 0;
NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
// TODO: Add your control notification handler code here
//获取列的排序数据
PLISTSORTNODE pItem = &m_tSortColumns[pNMListView->iSubItem];
pItem->pList = &m_ListCtrl;
pItem->nColum = pNMListView->iSubItem;
if ( pItem->nOrder == 0 )
{
pItem->nOrder = 1;
}
else
{
pItem->nOrder = 0;
}
m_ListCtrl.SortItems(CompareFunc,(LPARAM)pItem);
*pResult = 0;
}
int CALLBACK CCZLogAnalysisDlg::CompareFunc(LPARAM lParam1,LPARAM lParam2,LPARAM lParamSort)
{
PLISTSORTNODE pItem =(PLISTSORTNODE)lParamSort;
CListCtrl* list =pItem->pList;
int isub =pItem->nColum;
LVFINDINFO findInfo;
findInfo.flags = LVFI_PARAM;
findInfo.lParam = lParam1;
int iItem1 = list->FindItem(&findInfo, -1);
findInfo.lParam = lParam2;
int iItem2 = list->FindItem(&findInfo, -1);
CString strItem1 =list->GetItemText(iItem1,isub);
CString strItem2 =list->GetItemText(iItem2,isub);
const wchar_t* cItem1 = NULL;
const wchar_t* cItem2 = NULL;
cItem1 = strItem1.GetBuffer(sizeof(strItem1));
cItem2 = strItem2.GetBuffer(sizeof(strItem2));
////判断是否比较列是否为数值
//if ( isub == 2 )
//{
// int nNum1 = atoi( strItem1 );
// int nNum2 = atoi( strItem2 );
// if(pItem->nOrder == 0)
// return nNum1>nNum2 ? 1 : -1;
// else
// return nNum1>nNum2 ? -1 : 1;
//}
//else
//{
// if(pItem->nOrder == 0)
// return strcmp(strItem2, strItem1);
// else
// return -strcmp(strItem2, strItem1);
//}
if ( isub != 2 )
{
if(pItem->nOrder == 0)
return wcscmp(cItem2, cItem1);
else
return -wcscmp(cItem2, cItem1);
}
}
4.最重要的一步:
在控件InsertItem与SetItemText函数之间添加SetItemData函数。
//添加ListCtrl数据
int nRet; //m_ListCtrl为控件对应变量
nRet = m_ListCtrl.InsertItem( m_ListCtrl.GetItemCount( ), _T("http://www.a3gs.com ") );
//设置一个唯一的Item数据,否则无法排序
m_ListCtrl.SetItemData( nRet, 0 );
m_ListCtrl.SetItemText( nRet, 1, _T("天使知识授理厂") );
m_ListCtrl.SetItemText( nRet, 2, _T("100") );
nRet = m_ListCtrl.InsertItem( m_ListCtrl.GetItemCount( ), _T("http://www.a3gs.com") );
m_ListCtrl.SetItemData( nRet, 1 );
m_ListCtrl.SetItemText( nRet, 1, _T("Android") );
m_ListCtrl.SetItemText( nRet, 2, _T("20") );