i want to detect an item double click in a winform

2019-02-18 19:10发布

问题:

well i have a listbox with some items inside.
i want to detect a double click on an item.
currently the method i am using have a problem that if a user double click on an empty spot the currently selected item is signaled as double clicked.

Update:
Please note that this question is not as easy as it seems at first.
also note that Timwi answer is not correct because the [if (ListBox1.SelectedIndex == -1)] part dont get executed if there is an item selected and i clicked in an empty space i dont know who upvoted him but his answer is not correct.
i already had this part of code written
if there is a function that can convert mouse coordinates to a listbox item then the problem will be fixed

回答1:

There is an alternative event: MouseDoubleClick, which provides MouseEventArgs, so you can get click coordinates. Then you can call GetItemBounds() to get rectangle, containing selected item and check if mouse coordinates are within this rectangle:

    private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        if(listBox1.SelectedIndex != -1)
        {
            var rect = listBox1.GetItemRectangle(listBox1.SelectedIndex);
            if(rect.Contains(e.Location))
            {
                // process item data here
            }
        }
    }

MouseDoubleClick Version Information:

  • .NET Framework - Spported in: 4, 3.5, 3.0, 2.0
  • .NET Framework Client Profile - Supported in: 4, 3.5 SP1


回答2:

Here's what I used for a single MouseClick, might be adapted.

First I set the properties of the CheckListBox.CheckOnClick to true: clb.CheckOnClick = true;

then I forced the item to deselect after the box checkstate changed:

void clb_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if (clb.Items.Count > 0) { clb.SetSelected(0, false); }
    }