如何在鼠标光标下获取正确的ListViewItem?

时间:2019-03-10 05:29:24

标签: c# winforms listview

ListView.GetItemAt方法的问题显示在下面的屏幕截图中。

设计师代码

this.listView1 = new System.Windows.Forms.ListView();
this.SuspendLayout();
// 
// listView1
// 
this.listView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.listView1.Location = new System.Drawing.Point(0, 0);
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(717, 511);
this.listView1.TabIndex = 0;
this.listView1.UseCompatibleStateImageBehavior = false;
// 
// Form1
// 
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(717, 511);
this.Controls.Add(this.listView1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);

隐藏代码

public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
    listView1.OwnerDraw = true;
    listView1.View = View.LargeIcon;
    listView1.DrawItem += ListView1_DrawItem;
    listView1.MouseMove += ListView1_MouseMove;

    for (int i = 1; i <= 10; ++i)
    {
        listView1.Items.Add($"item {i}", 0);
    }
}

private void ListView1_MouseMove(object sender, MouseEventArgs e)
{
    ListViewItem item = listView1.GetItemAt(e.X, e.Y);

    if (LastHoveredItem != null)
    {
        ListViewItem item2 = LastHoveredItem;
        LastHoveredItem = null;
        listView1.Invalidate(item2.Bounds);
    }

    if (item != null)
    {
        LastHoveredItem = item;
        listView1.Invalidate(item.Bounds);
    }
    else
    {
        LastHoveredItem = null;
    }
}

private void ListView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
    if (LastHoveredItem == e.Item)
    {
        e.Graphics.FillRectangle(Brushes.Yellow, e.Item.Bounds);
    }
    else
    {
        e.Graphics.FillRectangle(Brushes.Green, e.Item.Bounds);
    }
}

internal ListViewItem LastHoveredItem = null;

屏幕截图

鼠标光标下方的矩形应为黄色,但与其他未悬停的矩形一样,为绿色。

screenshot

2 个答案:

答案 0 :(得分:1)

如果图标的标签或图标矩形包含该点,则

ListView.GetItemAt将获得该项目。这不是您要找的东西。您需要检查整个项目。

您可以使用以下两种方法之一:

示例-在DrawItem中检测热项

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
    //...
    var p = listView1.PointToClient(Cursor.Position);
    if (e.Item.GetBounds(ItemBoundsPortion.Entire).Contains(p))
    {
        //e.Item is Hot
    }
    else
    {
        //e.Item is Normal
    }
    //...
}

答案 1 :(得分:0)

为什么不能使用listView1.FocusedItem属性