C#列表框或DataGrid双击所选项目

C#列表框或DataGrid双击所选项目,c#,events,listbox,event-handling,mouseevent,C#,Events,Listbox,Event Handling,Mouseevent,从listbox或DataGrid返回所选项目时出现问题。问题是,我特别希望用户双击所选项目,而不是控件上的任何其他位置(就像双击事件一样)。 目前我有: private void listBox1_DoubleClick(object sender, EventArgs e) { if (listBox1.SelectedItem == null) return; System.Console.WriteLine(listBox1.SelectedIte

从listbox或DataGrid返回所选项目时出现问题。问题是,我特别希望用户双击所选项目,而不是控件上的任何其他位置(就像双击事件一样)。 目前我有:

private void listBox1_DoubleClick(object sender, EventArgs e)
    {
        if (listBox1.SelectedItem == null) return;
        System.Console.WriteLine(listBox1.SelectedItem.ToString()); //console for testing
    }
虽然它可以工作,但我不喜欢这样一个事实,即您可以单击一次某个项目,然后双击控件空白处的任意位置,然后返回以前选择的项目。有什么简单的方法可以更改它吗?

您应该在双击事件发生的位置获取项目:

int index = listBox1.IndexFromPoint(e.Location);
if (index != System.Windows.Forms.ListBox.NoMatches)
{
  System.Console.WriteLine(listBox1.SelectedItem.ToString()); //console for testing
}
您应该在双击事件发生的位置获取项目:

int index = listBox1.IndexFromPoint(e.Location);
if (index != System.Windows.Forms.ListBox.NoMatches)
{
  System.Console.WriteLine(listBox1.SelectedItem.ToString()); //console for testing
}

EventArgs在双击中没有位置。鼠标事件没有双击事件。我不知道如何实现这个…EventArgs在双击中没有位置。鼠标事件没有双击事件。我不知道如何实现这个。。。