views:

314

answers:

2

Hello. I would like to keep an item selected, on a ListView, when the user clicks on a space which has no item. For example, the space below the items, but still on the ListView component. I've change the ListView property "HideSelection" to false, but that only works when the focus is changed to another component; not when the user clicks on the ListView itself. Thanks!

A: 

One way: on the SelectedIndexChanged event, check to see if the value is -1; if so, reset it to the previous value (which you maybe stored in a variable...)

LesterDove
Do you know how would I get the index?
Joey Morani
+2  A: 

This is something you normally shouldn't fix. The user clicked somewhere intentionally, that might well be because she wanted to deselect an item. If it was unintentional then she'll understand what happened and know how to correct it. Giving standard controls non-standard behavior tends to only confuse the user.

But you can fix it. You'll need to prevent the native ListView control from seeing the click. That requires overriding the WndProc() method and checking where the click occurred. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto the form.

using System;
using System.Drawing;
using System.Windows.Forms;

class MyListView : ListView {
  protected override void WndProc(ref Message m) {
    if (m.Msg == 0x201 || m.Msg == 0x203) {  // Trap WM_LBUTTONDOWN + double click
      var pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16);
      var loc = this.HitTest(pos);
      switch (loc.Location) {
        case ListViewHitTestLocations.None:
        case ListViewHitTestLocations.AboveClientArea:
        case ListViewHitTestLocations.BelowClientArea:
        case ListViewHitTestLocations.LeftOfClientArea:
        case ListViewHitTestLocations.RightOfClientArea:
          return;  // Don't let the native control see it
      }
    }
    base.WndProc(ref m);
  }
}
Hans Passant
Wow. That works great! Just one thing though; is there a way to modify that code so it also works for a right-click as well? Thanks a lot!
Joey Morani
Right click is 0x202. It should display a context menu...
Hans Passant