Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MFC: How to change color/boldness of inidividual rows of ListCtrl?

Using MFC and Visual Studio 2010 C++. I need a way to make certain individual rows of a CListCtrl stand out (however I do not want to use the built-in selection capability to highlight the rows). It could be the color of the row background, or font weight, or possibly even an image (if that is performant).

Ideally I want to know how to do this using the stock list control. However, if this is not possible then let me know of a way using 3rd party code.

UPDATE

Here's the code I ended up using:

void MyList::OnNMCustomdraw(NMHDR *pNMHDR, LRESULT *pResult)
{
    NMLVCUSTOMDRAW* cd = reinterpret_cast<NMLVCUSTOMDRAW*>(pNMHDR);

    *pResult = CDRF_DODEFAULT;

    switch( cd->nmcd.dwDrawStage)
    {
        case CDDS_PREPAINT:
            *pResult = CDRF_NOTIFYITEMDRAW;
            break;

        case CDDS_ITEMPREPAINT:
            {
                int rowNumber = cd->nmcd.dwItemSpec;
                bool highlightRow = (bool)GetItemData(rowNumber);
                if (highlightRow)
                {
                    COLORREF backgroundColor;
                    backgroundColor = RGB(255, 0, 0);
                    cd->clrTextBk = backgroundColor;
                }
            }
            break;

        default:
            break;
    }
}

In my case, I wasn't using the ItemData for anything, so I called SetItemData elsewhere with a boolean value to indicate whether the row should be highlighted.

like image 750
User Avatar asked Jan 11 '12 16:01

User


1 Answers

The key message here is the NM_CUSTOMDRAW message sent to your CListCtrl (and some other controls). It allows you to tell Windows that you want to custom draw some part of the CListCtrl. The idea is that the message allows you tell which part of the control should be custom drawn. Because custom drawing the whole CListCtrl only to change the text color of a cell would be totally overkill.

Don't worry, you don't have to handle custom draw yourself: The message allows to set the font and/or text/back color for one specific row or cell of the control.

This codeproject article is probably a good starting point.

Here is a shorter code example to set the color of a specific line in your CListCtrl.

like image 126
Serge Wautier Avatar answered Nov 14 '22 02:11

Serge Wautier