Search code examples
delphiselectiondelphi-xe4tlistview

TListView doesn't hide selection when using explorer style


In Delphi XE4 if you set HideSelection to true and use an explorer style TListView (when the selection rectangle has a gradient background like Windows Explorer) clicking on another control will not hide the selection rectangle. It will stay there as if nothing has happened - it will not even turn into a gray rectangle like normally when the Listview doesn't have focus.

Is this a Delphi bug or a "feature" of the MS Listview control? Are there any known workarounds or fixes for this? It's really annoying...


Solution

  • This "feature" is explained by David, and here is a workaround.

    By utilizing the OnExit event to save the selection and set selection to nil, you would mimic the wanted behavior. When the ListView is focused, restore the selection. To make it react on the mouse, make the ListView focused in the OnMouseEnter event.

    Type
      TForm1 = class(TForm)
      ...
      private
        FSelected: TListItem;
      ...
      end;
    
    procedure TForm1.ListView1Enter(Sender: TObject);
    begin
      if (ListView1.SelCount = 0) and Assigned(FSelected) then
        ListView1.Selected := FSelected;
    end;
    
    procedure TForm1.ListView1Exit(Sender: TObject);
    begin
      FSelected := ListView1.Selected;
      if Assigned(FSelected) then ListView1.Selected := Nil;
    end;
    
    procedure TForm1.ListView1MouseEnter(Sender: TObject);
    begin
      ListView1.SetFocus;
    end;
    

    Having mentioned this solution, why not go for the simple one, set HideSelection = false, and the selected item will turn gray when unfocused, just like Sertac mentioned in a comment.