
Несколько примеров на Delphi для изменения цвета фона на разных строках в компоненте ListBox.
Перед тем как скомпилировать этот код, нужно в компоненте ListBox в свойстве Style изменить событие OnDrawItem на lbOwnerDrawFixed иначе пример работать не будет.
procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
var
myColor: TColor;
myBrush: TBrush;
begin
myBrush := TBrush.Create;
with (Control as TListBox).Canvas do
begin
if not Odd(Index) then
myColor := clSilver
else
myColor := clYellow;
myBrush.Style := bsSolid;
myBrush.Color := myColor;
Windows.FillRect(handle, Rect, myBrush.handle);
Brush.Style := bsClear;
TextOut(Rect.Left, Rect.Top, (Control as TListBox).Items[Index]);
myBrush.Free;
end;
end;
Rect: TRect; State: TOwnerDrawState);
var
myColor: TColor;
myBrush: TBrush;
begin
myBrush := TBrush.Create;
with (Control as TListBox).Canvas do
begin
if not Odd(Index) then
myColor := clSilver
else
myColor := clYellow;
myBrush.Style := bsSolid;
myBrush.Color := myColor;
Windows.FillRect(handle, Rect, myBrush.handle);
Brush.Style := bsClear;
TextOut(Rect.Left, Rect.Top, (Control as TListBox).Items[Index]);
myBrush.Free;
end;
end;
Еще один пример для изменения строк в ListBox. В этом примере можно установить цвет фона в ListBox только по номеру строки.
procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
begin
with (Control as TListBox).Canvas do
begin
case Index of
0:
begin
Font.Color := clBlue;
Brush.Color := clYellow;
end;
1:
begin
Font.Color := clRed;
Brush.Color := clLime;
end;
2:
begin
Font.Color := clGreen;
Brush.Color := clFuchsia;
end;
end;
FillRect(Rect);
TextOut(Rect.Left, Rect.Top, (Control as TListBox).Items[Index]);
end;
end;
Rect: TRect; State: TOwnerDrawState);
begin
with (Control as TListBox).Canvas do
begin
case Index of
0:
begin
Font.Color := clBlue;
Brush.Color := clYellow;
end;
1:
begin
Font.Color := clRed;
Brush.Color := clLime;
end;
2:
begin
Font.Color := clGreen;
Brush.Color := clFuchsia;
end;
end;
FillRect(Rect);
TextOut(Rect.Left, Rect.Top, (Control as TListBox).Items[Index]);
end;
end;