C# 右键单击以选择列表框中的项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9220501/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:25:49  来源:igfitidea点击:

Right Click to select items in a ListBox

c#winformsselectlistboxright-click

提问by Ipquarx

I'm trying to make a list of items that you can do several actions with by right-clicking and having a context menu come up. I've completed that, no problem whatsoever.

我正在尝试制作一个项目列表,您可以通过右键单击并出现上下文菜单来执行多个操作。我已经完成了,没有任何问题。

But I'd like to have it so that when you right click on a item, instead of leaving the current item selected, to select the item the mouse is over.

但是我想要它,以便当您右键单击一个项目时,而不是选择当前项目,而是选择鼠标悬停的项目。

I've researched this and other related questions, and I've tried to use indexFromPoint (which I found through my research) but whenever I right click on a item, it always just clears the selected item and doesn't show the context menu, as I have it set so that it wont appear if there is no selected item.

我研究了这个问题和其他相关问题,我尝试使用 indexFromPoint(我通过研究发现)但是每当我右键单击一个项目时,它总是只清除所选项目而不显示上下文菜单,因为我已经设置好了,如果没有选中的项目,它就不会出现。

Here is the code I'm currently using:

这是我目前使用的代码:

ListBox.SelectedIndex = ListBox.IndexFromPoint(Cursor.Position.X, Cursor.Position.Y);

采纳答案by demoncodemonkey

Handle ListBox.MouseDownand select the item in there. Like this:

处理ListBox.MouseDown并选择其中的项目。像这样:

private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
    listBox1.SelectedIndex = listBox1.IndexFromPoint(e.X, e.Y);
}

回答by Narottam Goyal

this one is working...

这个正在工作...

this.ListBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.List_RightClick);

private void List_RightClick(object sender, MouseEventArgs e)
{

    if (e.Button == MouseButtons.Right)
    {
        int index = this.listBox.IndexFromPoint(e.Location);
        if (index != ListBox.NoMatches)
        {
            listBox.Items[index];
        }
    }

}

回答by Dave Mateer

Can also get same behaviour by setting a MouseRightButtonUp event on the whole listbox then:

也可以通过在整个列表框上设置 MouseRightButtonUp 事件来获得相同的行为,然后:

private void AccountItemsT33_OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
    // If have selected an item via left click, then do a right click, need to disable that initial selection
    AccountItemsT33.SelectedIndex = -1;
    VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), (sender as ListBox)).OfType<ListBoxItem>().First().IsSelected = true;
}