How to change color of CListCtrl column

前端 未结 3 1131
北荒
北荒 2021-01-23 16:06

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(         


        
相关标签:
3条回答
  • 2021-01-23 16:40

    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.

    0 讨论(0)
  • 2021-01-23 16:45

    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;
    }
    
    0 讨论(0)
  • 2021-01-23 16:46

    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

    0 讨论(0)
提交回复
热议问题