Click to See Complete Forum and Search --> : text color in listbox!


October 13th, 1999, 03:24 PM
hi!
do anyone knoew how to chage the color in listbox control?
i mean each line in another color.

grial m

Thomas Ascher
October 14th, 1999, 02:50 AM
Hi, the easiest would be to set the style of the listbox in your dialog in resource editor to "owner draw fixed". Then you must catch the WM_DRAWITEM message in your dialog (use ClassWizard: select message WM_DRAWITEM and button Add member function). In this function you can draw your listbox items. the following example draws the listbox like the windows default:

void CMyDialog::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDraw)
{
if(nIDCtl != IDC_MYLISTBOX) // check if it is our listbox, if not call default
{
CMyDialog::OnDrawItem(nIDCtl, lpDraw);
return;
}

CDC* pDC = CDC::FromHandle(lpDraw->hDC);

if(lpDraw->itemID == -1) // no items in listbox
{
if(lpDraw->itemAction & ODA_FOCUS)
pDC->DrawFocusRect(&lpDraw->rcItem);
return;
}

CListBox* lb = (CListBox*)CWnd::FromHandle(lpDraw->hwndItem);
COLORREF crBack, crText;
CString strText;

// set foreground and background colors
if(lpDraw->itemState & ODS_SELECTED) // item is selected
{
crBack = pDC->SetBkColor(GetSysColor(COLOR_HIGHLIGHT));

if(lpDraw->itemState & ODS_DISABLED) // item is disabled
crText = pDC->SetTextColor(GetSysColor(COLOR_GRAYTEXT));
else
crText = pDC->SetTextColor(GetSysColor(COLOR_HIGHLIGHTTEXT));
}
else
{
crBack = pDC->SetBkColor(GetSysColor(COLOR_WINDOW));

if(lpDraw->itemState & ODS_DISABLED)
crText = pDC->SetTextColor(GetSysColor(COLOR_GRAYTEXT));
else
crText = pDC->SetTextColor(GetSysColor(COLOR_WINDOWTEXT));
}

lb->GetText(lpDraw->itemID, strText);
pDC->ExtTextOut(lpDraw->rcItem.left + 2, lpDraw->rcItem.top,
ETO_OPAQUE, &lpDraw->rcItem, strText, strText.GetLength(), NULL);

if(lpDraw->itemState & ODS_FOCUS) // if item has focus draw focus rectangle
{
CBrush black(RGB(0, 0, 0));
pDC->SetTextColor(RGB(255, 255, 255));
pDC->FrameRect(&lpDraw->rcItem, &black);
pDC->DrawFocusRect(&lpDraw->rcItem);
}

// select old colors
pDC->SetBkColor(crBack);
pDC->SetTextColor(crText);
}

November 2nd, 1999, 10:27 AM
Can anyone adapt this to only highlight a specific line of the list box, depending on the previous lines final character ?

I have some code that checks the last character of the current line being written to the listbox, at this point I want to change the background colour before writing the next line. Any suggestions.