How to create a TListBox with coloured entries (Views: 704)
Problem/Question/Abstract: I add protocol messages into a listbox, simple lines of text like "success" and "failed". Now I want to have a different background color for every item. For example the "failed" ones in red and the "successed" in green. How to achieve this? Answer: Put a TListBox on a form, call it ListBox1, set its style to "lbOwnerDrawFixed" and implement the following event: procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var Flags: Longint; begin with ListBox1 do begin { If the item is not selected, then...} if not (odSelected in State) then with Canvas.Brush do begin { Choose the appropriate color} case Index of 0: Color := clBlue; 1: Color := clRed; 2: Color := clGreen; end; end; { Draw the colored rectangle.} ListBox1.Canvas.FillRect(Rect); if Index < Items.Count then begin Flags := DrawTextBiDiModeFlags(DT_SINGLELINE or DT_VCENTER or DT_NOPREFIX); if not UseRightToLeftAlignment then Inc(Rect.Left, 2) else Dec(Rect.Right, 2); DrawText(Canvas.Handle, PChar(Items[Index]), Length(Items[Index]), Rect, Flags); end; end; end; |