Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Set Font colour of items in a TListbox

Status
Not open for further replies.

LucieLastic

Programmer
May 9, 2001
1,694
GB
hi

How can I set certain items in a list box to a different colour? I tried the following but didn't work

procedure TFormCoList.ListBoxCompaniesDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
begin
if index = 5 then
(Control as TListBox).Canvas.font.Color := clred
else (Control as TListBox).Canvas.font.Color := clblack;
end;

many thanks
lou
 
hi!

Sorted it!

procedure TFormCoList.ListBoxCompaniesDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
begin
(Control as TListBox).Canvas.FillRect(Rect);
if index = 5 then
(Control as TListBox).Canvas.font.Color := clred
else (Control as TListBox).Canvas.font.Color := clblack;
(Control as TListBox).Canvas.TextOut(Rect.Left, Rect.Top, (Control as TListBox).Items[Index]);
end;

lou
 
What you need to do is set the Style property of the TListBox to lbOwnerDrawFixed then add the following code to the OnDrawItem event of the ListBox. If you don't change the Style property then the OnDrawItem event is not called.
Code:
procedure TForm3.ListBox1DrawItem(Control: TWinControl; Index: Integer;
  Rect: TRect; State: TOwnerDrawState);
var
    myColor: TColor;
    myBrush: TBrush;      
begin
  myBrush := TBrush.Create;  
  with (Control as TListBox).Canvas do // draw on control canvas, not on the form
  begin
    if Index = 3 then
      myColor := clRed
    else
      myColor := clBlack;

    myBrush.Style := bsSolid; 
    myBrush.Color := myColor; 

    Windows.FillRect(handle, Rect, myBrush.Handle); 

    Brush.Style := bsClear;  
    // display the text 
    TextOut(Rect.Left, Rect.Top, (Control as TListBox).Items[Index]);  
    MyBrush.Free;
  end;
end;
Clive [infinity]

Don't forget what Christmas is all about: not [santa2] but Jesus!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top