Application/MFC

[MFC] CListControl 정렬 기능 구현

devsalix 2022. 12. 23. 15:04
728x90
반응형

 

우선 CListControl 컨트롤의 속성에서

 

HDN_ITEMCLICK 이벤트를 추가해 줍니다

 

그런 다음 헤더 파일 상단에 구조체 하나를 선언해 줍니다

 

struct PARAMSORT
{
    PARAMSORT(HWND hWnd, int columnIndex, BOOL ascending)
        :m_hWnd(hWnd)
        ,m_ColumnIndex(columnIndex)
        ,m_Ascending(ascending)
    {}

    HWND m_hWnd;
    int  m_ColumnIndex;
    BOOL m_Ascending;
};

 

추가로 헤더 파일에

 

Ascending 할것인지 아닌지를 설정하기 위해 클릭했던 Colume을 기억할 변수를 선언합니다

 

int m_iSortIndex;

 

이후 cpp 파일에 CALLBACK 함수를 하나 추가 합니다

 

int CALLBACK SortFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
    PARAMSORT& ps = *(PARAMSORT*)lParamSort;

    TCHAR left[256] = _T(""), right[256] = _T("");
    ListView_GetItemText(ps.m_hWnd, lParam1, 
        ps.m_ColumnIndex, left, sizeof(left));
    ListView_GetItemText(ps.m_hWnd, lParam2, 
        ps.m_ColumnIndex, right, sizeof(right));    

    if (ps.m_Ascending)
        return _tcscmp( left, right );
    else
        return _tcscmp( right, left );            
}

 

마지막으로 선언된 HDN_ITEMCLICK 이벤트 함수에서 아래와 같이 코드를 작성합니다

 

void CDlg::OnHdnItemclickList1(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMHEADER phdr = reinterpret_cast<LPNMHEADER>(pNMHDR);
	// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
	*pResult = 0;

	int iCol = phdr->iItem;
	BOOL bAscending;

	if(iCol >= 0)
	{
		if(m_iSortIndex == iCol)
		{
			m_iSortIndex = -1;
			bAscending = TRUE;
		}
		else
		{
			m_iSortIndex = iCol;
			bAscending = FALSE;
		}

		PARAMSORT paramsort(m_ListCtrlClient.GetSafeHwnd(), iCol, bAscending);
		m_ListCtrlClient.SortItemsEx(SortFunc, (DWORD)&paramsort);
	}
}

 

끝!!

 

참고 : https://www.codeproject.com/Articles/27774/CListCtrl-and-sorting-rows

 

CListCtrl and sorting rows

Examples of how to sort rows in the MFC list control.

www.codeproject.com

 

728x90
반응형