Winforms ListView MouseUp event firing more than once

怎甘沉沦 提交于 2019-12-24 05:00:10

问题


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


来源:https://stackoverflow.com/questions/25320945/winforms-listview-mouseup-event-firing-more-than-once

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