[C/CPP] CListCtrl 리스트 컨트롤에 기본적인 Sort 기능 추가하는 방법 - WEBSHARE

[C/CPP] CListCtrl 리스트 컨트롤에 기본적인 Sort 기능 추가하는 방법

메시지 맵에 통지 메시지를 추가시킨다.

ON_NOTIFY(HDN_ITEMCLICKA, 0, OnHdnItemclick)
ON_NOTIFY(HDN_ITEMCLICKW, 0, OnHdnItemclick)

 

헤더에함수 정의를 해준다.

afx_msg void OnHdnItemclick(NMHDR *pNMHDR, LRESULT *Result);
static int CALLBACK SortFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort);

 

헤더에 필요한 관련 구조체화 변수를 public 형식으로 추가해준다.

BOOL m_bAscending;

struct HSORTITEM
{
    CListCtrl* pSortItem;
    int iColumn;
};

 

함수를 구현한다.

void CFileList::OnHdnItemclick(NMHDR *pNMHDR, LRESULT *pResult)
{
    LPNMHEADER phdr = NULL;
    phdr = reinterpret_cast<LPNMHEADER>(pNMHDR);
    HSORTITEM item;
    item.iColumn = phdr->iItem;
    item.pSortItem = this;

    // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
    SortItems(SortFunc, (LPARAM)&item);

    m_bAscending = !m_bAscending;
}


int CALLBACK CFileList::SortFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
    HSORTITEM* pItem = (HSORTITEM*)lParamSort;
    CFileList *pListCtrl = (CFileList*)pItem->pSortItem;
    BOOL bascending = pListCtrl->m_bAscending;

    LVFINDINFO info1, info2;
    info1.flags = LVFI_PARAM;
    info1.lParam = lParam1;
    info2.flags = LVFI_PARAM;
    info2.lParam = lParam2;
    int irow1 = pListCtrl->FindItem(&info1,-1);
    int irow2 = pListCtrl->FindItem(&info2,-1);

    CString strItem1 = pListCtrl->GetItemText(irow1, pItem->iColumn);
    CString strItem2 = pListCtrl->GetItemText(irow2, pItem->iColumn); 

    // 특정 필드에 숫자가 있다면 이런방식도 나쁘지 않다. 조건은 편하게 걸면 된다.
    if(pItem->iColumn == 1)
    {
        int nRetVal = 0;
        int size1 = _ttoi(strItem1);
        int size2 = _ttoi(strItem2);

        if(size1 == size2) nRetVal = 0;

        if(size1 < size2) nRetVal = -1;
        if(size1 > size2) nRetVal = 1;

        return bascending? nRetVal : -nRetVal;
    }

    return bascending? _tcscmp(strItem1, strItem2) : -_tcscmp(strItem1, strItem2);
}

게시됨

카테고리

작성자

태그:

댓글

“[C/CPP] CListCtrl 리스트 컨트롤에 기본적인 Sort 기능 추가하는 방법” 에 하나의 답글

  1. 김주환 아바타

    뭐야. 몰라서 검색하고 들어왔는데, 내 블로그잖아? -_-;

댓글 남기기