C# 在列表视图控件中获取鼠标光标下的项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1045621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the item under mouse cursor in a listview control?
提问by Joan Venge
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.
所以我不使用鼠标事件,但键盘事件当然不会给我 ListViewItem。
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?
有任何想法吗?
回答by Fredrik M?rk
If you know which ListView control you are interested in, the following method will do the trick:
如果你知道你对哪个 ListView 控件感兴趣,下面的方法就可以解决问题:
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);
回答by Daniel Earwicker
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.
只是要记住一些事情,否则你会得到一个“独特的”(令人困惑的)用户交互。