Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the item under mouse cursor in a listview control?

Basically I am trying to implement a feature where if the user presses a key, I want to find out the item under the mouse cursor.

So I don't use Mouse events but Keyboard events which doesn't give me a ListViewItem of course.

I just don't know in what space I need to get the mouse position and convert it into the control's space.

Any ideas?

like image 993
Joan Venge Avatar asked Dec 06 '22 05:12

Joan Venge


1 Answers

If you know which ListView control you are interested in, the following method will do the trick:

private ListViewItem GetItemFromPoint(ListView listView, Point mousePosition)
{
    // translate the mouse position from screen coordinates to 
    // client coordinates within the given ListView
    Point localPoint = listView.PointToClient(mousePosition);
    return listView.GetItemAt(localPoint.X, localPoint.Y);
}

// call it like this:
ListViewItem item = GetItemFromPoint(myListView, Cursor.Position);
like image 108
Fredrik Mörk Avatar answered Dec 09 '22 16:12

Fredrik Mörk