views:

871

answers:

4

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?

+6  A: 

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);
Fredrik Mörk
Thanks Fredrik, I will try this today.
Joan Venge
+1  A: 

This devX article talks about what you are looking to do.

Matthew Vines
A: 

A keyboard action that depends on the mouse position sounds a little unorthodox. Keyboard actions should normally effect some item that is highlighted/focused/selected on the screen, either selected by previous keyboard actions or by a previous mouse click on that item.

Just something to bear in mind, or you'll wind up with a "unique" (confusing) user interaction.

Daniel Earwicker
Don't worry man, I am adding this feature for myself to ease the development for myself. It's not gonna be in the final version :)
Joan Venge
A: 

how is in WPF? how is in WPF? how is in WPF?

Musa Doğramacı