Default
Google

How can I change the color of certain items?

Applies To: C++Builder 1 or higher
Category: Knowledge Base

I can change the color of all items using the Font property. But is it possible to modify only some of these items? For example, I need to change the color of all items starting with C.
 
 
 1.
  Start a new project using File | New Application.
 
 2.
  Add a ListBox. Add the following items: Borland, Component,
      Thread and Capture. Set the Style to lbOwnerDrawFixed. Double-click
      its OnDrawItem event:
 
void __fastcall TForm1::ListBox1DrawItem(TWinControl *Control, int
    Index, TRect &Rect, TOwnerDrawState State)
{
    ListBox1->Canvas->FillRect(Rect);
    if(State.Contains(odSelected))
        ListBox1->Canvas->Font->Color = clHighlightText;
    else
    {
        if(ListBox1->Items->Strings[Index][1] == 'C')
            ListBox1->Canvas->Font->Color = clBlue;
        else
            ListBox1->Canvas->Font->Color = clBtnText;
    }
    ListBox1->Canvas->TextOut(Rect.Left + 2, Rect.Top,
        ListBox1->Items->Strings[Index]);
}
 
When the Style of your ListBox is owner drawn, you can use the OnDrawItem event to paint on the Canvas. The previous code fills the rectangle with the default color. Then it looks if the item is selected. If yes, it sets the font color to the default highlight text color. If not, it checks if the word begins with a C and sets the color to blue. Finally, it prints the text on the ListBox Canvas.

C++Builder Developer's Network
Copyright © Yoto Yotov



Acquiring image from ProHosting Banner Exchange