MFC:如何更改 ListCtrl 个别行的颜色/粗体?

2022-01-12 00:00:00 row visual-c++ highlighting mfc clistctrl

使用 MFC 和 Visual Studio 2010 C++.我需要一种方法来突出 CListCtrl 的某些单独的行(但是我不想使用内置的选择功能来突出显示这些行).它可能是行背景的颜色,或字体粗细,甚至可能是图像(如果这是高性能的话).

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).

理想情况下,我想知道如何使用库存列表控件来做到这一点.但是,如果这不可能,请告诉我使用 3rd 方代码的方法.

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.

更新

这是我最终使用的代码:

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;
    }
}

在我的例子中,我没有将 ItemData 用于任何事情,所以我在其他地方调用了 SetItemData,并使用一个布尔值来指示是否应该突出显示该行.

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.

推荐答案

这里的关键信息是 NM_CUSTOMDRAW 消息发送到您的 CListCtrl(和其他一些控件).它允许您告诉 Windows 您要自定义绘制 CListCtrl 的某些部分.这个想法是消息允许您告诉控件的哪个部分应该自定义绘制.因为自定义绘制整个 CListCtrl 只是为了更改单元格的文本颜色将完全是矫枉过正.

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.

这篇 codeproject 文章可能是一个很好的起点.

This codeproject article is probably a good starting point.

这是一个较短的代码示例,用于设置 CListCtrl 中特定行的颜色.

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

相关文章