Reputation: 907
I want to change the color of the LVITEM? m_szList is the CListCtrl.
LVITEM lvItem;
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 0;
lvItem.iSubItem = 0;
lvItem.pszText = _T("Sandra");
m_szList.InsertItem(&lvItem);
m_szList.SetTextColor(RGB(255, 78, 12));
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 1;
lvItem.iSubItem = 0;
lvItem.pszText = _T("Roger");
m_szList.InsertItem(&lvItem);
This code can change the both color of sandra and roger. But i just want to change the color of sandra to red. And roger to default(black).
Upvotes: 2
Views: 1504
Reputation: 490128
You can use a Custom-draw list control for this job.
You make the control custom draw by responding to the NM_CUSTOMDRAW
message. This is notification message that's sent from the control. Using MFC, your function header will look something like this:
void CCustomLvView::OnNMCustomdraw(NMHDR *pNMHDR, LRESULT *pResult)
To add this handler, you normally use the Properties list for the CListCtrl (or CListView), something like this:
That'll create a handler something like this:
void CCustomLV2View::OnNMCustomdraw(NMHDR *pNMHDR, LRESULT *pResult) {
LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR);
*pResult = CDRF_DODEFAULT;
}
[If memory serves, it also has a comment or two.]
You'll need to add a little code to that to change the text color, something on this order:
void CCustomLV2View::OnNMCustomdraw(NMHDR *pNMHDR, LRESULT *pResult) {
LPNMLVCUSTOMDRAW pNMCD = reinterpret_cast<LPNMLVCUSTOMDRAW>(pNMHDR);
*pResult = CDRF_DODEFAULT;
switch (pNMCD->nmcd.dwDrawStage) {
// this tells the control, before any painting begins, that we
// want to be notified just before any item in the control is drawn.
case CDDS_PREPAINT:
*pResult = CDRF_NOTIFYITEMDRAW;
break;
// This will be called before an item is drawn.
// We check what item is being drawn, and set the text color appropriately
case CDDS_ITEMPREPAINT:
if (pNMCD->nmcd.dwItemSpec == 0)
pNMCD->clrText = RGB(0, 0, 0);
else
pNMCD->clrText = RGB(255, 78, 12);
break;
}
}
As it is right now, this draws the text for the first item in black, and all subsequent items in your shade of red. The if (pNMCD->nmcd.dwItemSpec == 0)
is what chooses the items, and (of course) the pNMCD->clrText = RGB...
is what sets the text color.
Also note that I've made a fairly minor modification to the code it generates, so I have a LPNMLVCUSTOMDRAW
instead of a LPNMCUSTOMDRAW
. This gives access to the ListView-specific fields passed to the custom-draw handler. Without that, we don't get access to some of (any of?) the fields we're using.
Upvotes: 4