How to keep an item selected? - ListView

穿精又带淫゛_ 提交于 2019-12-04 20:10:50

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());
      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);
  }
}

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...)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!