获取光标下的项目在ListView控件?光标、控件、项目、ListView

2023-09-04 05:23:08 作者:"__ 輪 徊。

基本上,我想实现的地方,如果用户presses的关键,我想找出鼠标光标下的项的功能。

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.

所以我不使用鼠标事件,但键盘事件,不给我当然是ListViewItem的。

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.

任何想法?

推荐答案

如果你知道你有兴趣在ListView控件,下面的方法将这样的伎俩:

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);