Getting the item under mouse cursor in a listview control?

18,508

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);
Share:
18,508
Joan Venge
Author by

Joan Venge

Professional hitman.

Updated on June 07, 2022

Comments

  • Joan Venge
    Joan Venge almost 2 years

    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?