ListView highlighting effects (and how to force it to keep highlight when lost focus)

 

Many people ask about how to force a List View to keep the selected item highlight when the control lost its focus.

The obvious and fast answer is: Set “HideSelection” property to false, as it seems to be designed with such purpose. In part, this is true, because when the the list view losses the focus the item remains highlighted, but with the “inactive” color, instead the default highlight one.

A VERY EASY way to achieve is:

1.- Mark your list view as “Owner Draw” (OwnerDraw property = true)

2.- Write an event handler for the even “DrawItem” or “DrawSubItem” of the list view, doing something like this:

 

private void lvModelsInfo_DrawItem(object sender, DrawListViewItemEventArgs e)
       {
           if (e.Item.Selected)
           {
               e.Graphics.FillRectangle(new SolidBrush(COLOR1), e.Bounds);
               e.Graphics.DrawString(e.Item.Text, listview1.Font, COLOR2, e.Bounds.Location);
           }
           else
           {
               e.Graphics.DrawString(e.Item.Text, listview1.Font, COLOR3, e.Bounds.Location);
           }
       }

 

Et´voila. The list view keeps the highlight.

In addition to that, I´ve marked three variables: COLOR1, COLOR2 AND COLOR3. This vars allow you to customize the selection highlight color, item fore color (when selected), and item fore color (when not selected), respectively.

Hope this helps.

Cheers!