【问题标题】:Winforms ListView MouseUp event firing more than onceWinforms ListView MouseUp 事件多次触发
【发布时间】:2014-08-15 03:42:57
【问题描述】:

在我的 .NET 4,5 Winforms 应用程序中,当我从该事件中打开文件时,ListView 控件的 MouseUp 事件会触发多次,如下所示:

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

注意:单击列表视图的 SubItem1 时,文件打开,但消息框至少出现两次。但是,当我注释掉打开文件的行时,消息框只出现一次(应该如此)。我确实需要打开用户在列表视图中单击名称的文件。在没有多次触发 MoueUp 事件的情况下如何实现这一点? 另请注意,列表视图的 MouseClick 事件并不总是像 stated here 那样工作。所以,我必须使用 MouseUp 事件。

编辑:我应该提到 ListView 处于详细信息模式。

【问题讨论】:

    标签: c# winforms listview .net-4.5


    【解决方案1】:

    避免使用HitTest() 并使用ListView 的本机函数GetItemAt()。来自 MSDN 的示例如下所示:

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

    【讨论】:

    • 为什么要避免 HitTest()?我已经测试过,它在 MouseDown() 事件中运行良好。问题出在 MouseUp() 事件中。
    • 嗨@dotNET,您的解决方案有效 - 您介意解释一下原因吗?
    猜你喜欢
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多