Winforms ListView MouseUp event firing more than o

2019-07-21 14:19发布

问题:

In my .NET 4,5 Winforms application, the ListView control's MouseUp event is firing multiple times when I open a file from that event as follows:

private void ListView1_MouseUp(object sender, MouseEventArgs e)
{
   ListViewHitTestInfo hit = ListView1.HitTest(e.Location);

   if (hit.SubItem != null && hit.SubItem == hit.Item.SubItems[1])
   {
      System.Diagnostics.Process.Start(@"C:\Folder1\Test.pdf");
      MessageBox.Show("A test");
   }
}

Note: When clicking on the SubItem1 of the listview, the file opens but the message box appears at least twice. But, when I comment out the line that opens the file the message box appears only once (as it should). I do need to open the file whose name is clicked by the user in the listview. How can I achieve this without the MoueUp event firing multiple times? Please also note that the MouseClick event for listview does not always work as also stated here. So, I have to use MouseUp event.

EDIT: I should mention the ListView is in Details mode.

回答1:

Avoid HitTest() and use ListView's native function GetItemAt(). An example from MSDN looks like this:

private void ListView1_MouseDown(object sender, MouseEventArgs e)
{

    ListViewItem selection = ListView1.GetItemAt(e.X, e.Y);

    // If the user selects an item in the ListView, display 
    // the image in the PictureBox. 
    if (selection != null)
    {
        PictureBox1.Image = System.Drawing.Image.FromFile(
            selection.SubItems[1].Text);
    }
}