How to change color of CListCtrl column

我的梦境 提交于 2019-12-02 11:47:56

问题


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


回答1:


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.




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/19682479/how-to-change-color-of-clistctrl-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!