views:

116

answers:

1

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

+2  A: 

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
max
yeah this i what i was looking for , thanks :)
Karim