12

Is is possible to change the item selection focus color and text color in a TListBox?

When themes are not enabled in the project, or the list box style is set to owner-draw, the selection around the item is painted blue, which I believe is globally defined by the system's appearance settings.

I would like to change the color of selected items to a custom color.

So an example, the result would be something like this:

enter image description here

Note the last listbox has been modified in Paint to illustrate the example.

3 Answers 3

20

try this:

procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
  Rect: TRect; State: TOwnerDrawState);
begin
  with (Control as TListBox).Canvas do
  begin
    if odSelected in State then
      Brush.Color := $00FFD2A6;

    FillRect(Rect);
    TextOut(Rect.Left, Rect.Top, (Control as TListBox).Items[Index]);
    if odFocused In State then begin
      Brush.Color := ListBox1.Color;
      DrawFocusRect(Rect);
    end;
  end;
end;
4
  • 4
    @Craig - Make sure users do not have similar window text color. Dec 19, 2011 at 18:52
  • Thanks @Sertac I will consider that.
    – user741875
    Dec 22, 2011 at 14:04
  • Tried this but the TForm1.ListBox1DrawItem procedure is never called, i put a breakpoint on it and it never stops on this. What am i missing ? Jun 28, 2017 at 14:16
  • Doesn't that require ListBox1.Style to be one of the lbOwnerDrawXxxx values?
    – dummzeuch
    Jun 29, 2017 at 7:31
1

I saw, Style property has to be lbOwnerDrawFixed

0

This helped me do something I needed to do also, namely, eliminate any visible selection. I modified the code above very slightly to accomplish this:

procedure TForm1.OnDrawItem(Control: TWinControl; Index: Integer;
  Rect: TRect; State: TOwnerDrawState);
begin
  with (Control as TListBox).Canvas do
  begin
    if odSelected in State then
    begin
      Brush.Color := clWhite;
      Font.Color := clBlack;
    end;

    FillRect(Rect);
    TextOut(Rect.Left, Rect.Top, (Control as TListBox).Items[Index]);
    if odFocused In State then begin
      Brush.Color := ListBox1.Color;
      DrawFocusRect(Rect);
    end;
  end;
end;

Made the selected item's background color white, and it's font color black, which did what I needed. Thanks so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.