alex555
alex555

Reputation: 1786

How to change color of CListCtrl column

I want to change the background color of a specific column to a color of the dialog (grey). How can I achive it?

void CUcsOpTerminalDlg::OnCustomdrawFeatureList(NMHDR *pNMHDR, LRESULT *pResult)
{
  LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR);

  // TODO: change color 

  *pResult = 0;
}

Thanks

Upvotes: 1

Views: 6751

Answers (4)

Anthony Consolati
Anthony Consolati

Reputation: 81

For any poor soul still struggling to get this to work in 2022, this is the correct answer: https://stackoverflow.com/a/19701300/5117411

However you MUST ALSO change the first line of your message map declaration in your derived list class, from:

BEGIN_MESSAGE_MAP(VV_Page_List_Box, CListCtrl)

to

BEGIN_MESSAGE_MAP(VV_Page_List_Box, CMFCListCtrl)

otherwise your virtual override for OnGetCellBkColor will not get called!

Upvotes: 0

MikMik
MikMik

Reputation: 3466

If you are using the "new" MFC Feature Pack classes (VS 2008 SP1 and up), you can use CMFCListCtrl instead of CListCtrl and use CMFCListCtrl::OnGetCellBkColor.

You would have to derive your own class from it and override CMFCListCtrl::OnGetCellBkColor. There, just check the column index and return the background color you need:

COLORREF CMyColorfulListCtrl::OnGetCellBkColor(int nRow,int nColumn)
{
    if (nColumn == THE_COLUMN_IM_INTERESTED_IN)
    {
        return WHATEVER_COLOR_I_NEED;
    }
    return CMFCListCtrl::OnGetCellBkColor(nRow, nColumn);
}

Or, if you need the dialog to make the decission, you can query the dialog from that function:

COLORREF CMyColorfulListCtrl::OnGetCellBkColor(int nRow,int nColumn)
{
    COLORREF color = GetParent()->SendMessage(UWM_QUERY_ITEM_COLOR, nRow, nColumn);

    if ( color == ((COLORREF)-1) ) 
    { // If the parent doesn't set the color, let the base class decide
        color = CMFCListCtrl::OnGetCellBkColor(nRow, nColumn);
    }    
    return color;
}

Note that UWM_QUERY_ITEM_COLOR is a custom message. I usually use Registered Windows Messages as explained here.

Upvotes: 2

Abraxas
Abraxas

Reputation: 131

The custom draw API does not work exactly as advertised. Anyway, the following code will paint the second column green:

LPNMLVCUSTOMDRAW pNMLVCD = reinterpret_cast<LPNMLVCUSTOMDRAW>(pNMHDR);
*pResult = CDRF_DODEFAULT;
switch( pNMLVCD->nmcd.dwDrawStage )
{
case CDDS_PREPAINT:
    *pResult = CDRF_NOTIFYITEMDRAW;
    break;

case CDDS_ITEMPREPAINT:
    *pResult = CDRF_NOTIFYSUBITEMDRAW;
    break;

case CDDS_ITEMPREPAINT | CDDS_SUBITEM:
    if( pNMLVCD->iSubItem == 1 )
        pNMLVCD->clrTextBk = RGB(0,255,0);
    break;
}

Upvotes: 0

xMRi
xMRi

Reputation: 15375

Short answer: Fill the clrText and clrText Bk fields in the CDDS_ITEMPREPAINT phase.

Best article I ever read about this. Part 1, Part 2

Upvotes: 0

Related Questions