1. 程式人生 > 其它 >Win32 ListCtrl控制元件點選列標題排序

Win32 ListCtrl控制元件點選列標題排序

1.在WM_NOTIFY訊息中捕獲滑鼠點點選列的索引

int MyMainDialog::OnNotify(NMHDR* pNMhdr)
{
    if (pNMhdr->idFrom == IDC_LIST1)
    {
        QListCtrl listCtrl(pNMhdr->idFrom, this);
        NMLISTVIEW* pNmListView = (NMLISTVIEW*)pNMhdr;

        switch (pNMhdr->code)
        {
        case LVN_COLUMNCLICK:
        {
            
//獲得點選的列的索引 int nCol = pNmListView->iSubItem;
//獲得列標題中圖示的索引 int nColImage = listCtrl.GetColumnImageIndex(nCol);
//SortItemFunc自己定義的排序回撥函式,第二個引數傳二個值(列索引,升序=0/降序=1)
        //這個函式就是向ListCtrl控制元件傳送的LVM_SORTITEMS訊息
listCtrl.SortItem(SortItemFunc, MAKELPARAM(nCol, nColImage));
//排序後把圖示索引改變(就在0和1之間) listCtrl.SetColumnImageIndex(nCol, (nColImage == 0 ? 1 : 0)); }break; case LVN_DELETEITEM: //關閉視窗後刪除行中儲存New出來的記憶體地址 { if (pNmListView->lParam != 0) { delete (StudentStruct*)pNmListView->lParam; pNmListView
->lParam = 0; } }break; } } return 0; }

2.自定義回撥函式SortItemFunc

int CALLBACK SortItemFunc(LPARAM lParam1, LPARAM lParam2, LPARAM sortID)
{
    //要比較的兩行資料
  //這兩行的資料是儲存在行的lParam資料中
  //用SetItemData賦值的
StudentStruct* pStu1 = (StudentStruct*)lParam1; StudentStruct* pStu2 = (StudentStruct*)lParam2; int nCol = LOWORD(sortID); //要比較的列索引 int nAcs = HIWORD(sortID); //按升序或是降序排序 int nRet = 0; switch (nCol) { case 0: //姓名 nRet = _tcscmp(pStu1->name, pStu2->name); break; case 1: //性別 nRet = _tcscmp(pStu1->sex, pStu2->sex); break; case 2: //年齡,這是字元比較,如果是數字比較就要自己處理<,=,>的結果 //nRet = _tcscmp(pStu1->age, pStu2->age); if (pStu1->age < pStu2->age) nRet = -1; if (pStu1->age == pStu2->age) nRet = 0; if (pStu1->age > pStu2->age) nRet = 1; break; case 3: //電話 nRet = _tcscmp(pStu1->tel, pStu2->tel); break; } return (nAcs == 0 ? nRet : -nRet); }

點選性別示意圖

點選年齡示意圖

點選姓名示意圖

感覺林這個性沒排對,不只為啥?