更新时间:2021-08-19 22:12:15
嗨阿普尔瓦,
这是一种可能的解决方案:忽略在ListView的客户端区域中单击鼠标的操作.
Hi Apurva,
This is one possible solution for this: Ignore the mouse-click in the client area of the ListView.
using System;
using System.Windows.Forms;
using System.Drawing;
namespace ListViewFocusDemo
{
static class Program
{
class MyListView : ListView
{
protected override void WndProc(ref Message msg)
{
// Ignore mouse messages not in the client area
if (msg.Msg >= 0x201 && msg.Msg <= 0x209)
{
Point pointMousePos = new Point(msg.LParam.ToInt32() & 0xffff, msg.LParam.ToInt32() >> 16);
ListViewHitTestInfo lvhti = this.HitTest(pointMousePos);
switch (lvhti.Location)
{
case ListViewHitTestLocations.AboveClientArea:
case ListViewHitTestLocations.BelowClientArea:
case ListViewHitTestLocations.LeftOfClientArea:
case ListViewHitTestLocations.RightOfClientArea:
case ListViewHitTestLocations.None:
return;
}
}
base.WndProc(ref msg);
}
}
static void Main()
{
// Create a ListView
MyListView listview = new MyListView();
listview.Dock = DockStyle.Fill;
listview.View = View.Details;
listview.CausesValidation = false;
// ... add some columns
listview.Columns.Add("Name");
listview.Columns.Add("Value");
// ... and dummy items
listview.Items.Add(new ListViewItem(new string[] { "IsListView", "Yes" }));
listview.Items.Add(new ListViewItem(new string[] { "IsDoingWhatIWant", "No"}));
Label label = new Label();
label.Dock = DockStyle.Bottom;
listview.SelectedIndexChanged += delegate(object obj, EventArgs ea)
{
label.Text = String.Format("Selected Index = {0}",
listview.SelectedIndices.Count > 0 ? listview.SelectedIndices[0] : -1);
};
// Create a Test-Form
Form form = new Form();
form.Controls.Add(listview);
form.Controls.Add(label);
Application.Run(form);
}
}
}
另一个解决方案是,如果发生取消选择(SelectedIndexChanged,ItemSelectionChanged),则重新创建选择.
Another solution would be to recreate the selection if the unselection occurs (SelectedIndexChanged, ItemSelectionChanged).
listView1_SelectedIndeChaned(object sender, EventArgs e)
{
try
{
// your code here
}
catch
{
// leave empty to catch error
}
}