Author: Tomas Rutkauskas
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:
1 2 procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
3 Rect: TRect; State: TOwnerDrawState);
4 var5 Flags: Longint;
6 begin7 with ListBox1 do8 begin9 { If the item is not selected, then...}10 ifnot (odSelected in State) then11 with Canvas.Brush do12 begin13 { Choose the appropriate color}14 case Index of15 0: Color := clBlue;
16 1: Color := clRed;
17 2: Color := clGreen;
18 end;
19 end;
20 { Draw the colored rectangle.}21 ListBox1.Canvas.FillRect(Rect);
22 if Index < Items.Count then23 begin24 Flags := DrawTextBiDiModeFlags(DT_SINGLELINE or DT_VCENTER or DT_NOPREFIX);
25 ifnot UseRightToLeftAlignment then26 Inc(Rect.Left, 2)
27 else28 Dec(Rect.Right, 2);
29 DrawText(Canvas.Handle, PChar(Items[Index]), Length(Items[Index]), Rect,
30 Flags);
31 end;
32 end;
33 end;