如何使用鼠标右键选择ListBox中的项?(C#)

3
我尝试了很多方法并进行了数小时的研究,但它似乎从未对我起作用。
这是我的当前代码,我不知道为什么它不起作用。
    private void listBox1_MouseDown(object sender, MouseEventArgs e)
    {
        listBox1.SelectedIndex = listBox1.IndexFromPoint(e.X, e.Y);
        if (e.Button == MouseButtons.Right)
        {
            contextMenuStrip1.Show();
        }
    }

我并不关心可以移除的上下文菜单,我只是想找到一种方法让鼠标右键选择我点击的项目。

有什么想法吗?


如果您在方法中设置了断点,当您按下鼠标右键时,会触发它吗?还是左键? - Sam Holder
我似乎完全没有击中它。 - user1194782
然后你需要调查为什么根本没有命中它。方法是否绑定到组合框的事件上?(通常这是由设计器在InitializeComponent()函数中添加的) - Sam Holder
我不知道如何将它绑定到事件上。 - user1194782
5个回答

8
您离成功很近了,只是忘记选择项目。修复方法如下:
    private void listBox1_MouseUp(object sender, MouseEventArgs e) {
        if (e.Button == MouseButtons.Right) {
            var item = listBox1.IndexFromPoint(e.Location);
            if (item >= 0) {
                listBox1.SelectedIndex = item;
                contextMenuStrip1.Show(listBox1, e.Location);
            }
        }
    }

2
  private void lstFiles_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)   //(1)
        {
            int indexOfItemUnderMouseToDrag;
            indexOfItemUnderMouseToDrag = lstFiles.IndexFromPoint(e.X, e.Y); //(2)
            if (indexOfItemUnderMouseToDrag != ListBox.NoMatches)
            {
                lstFiles.SelectedIndex = indexOfItemUnderMouseToDrag; //(3)
            }
        }
    }

你能添加一些正在发生的描述吗? - dmportella

0
    private void listBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button== MouseButtons.Right)
        {
            int nowIndex = e.Y / listBox1.ItemHeight;
            if (nowIndex < listBox1.Items.Count)
            {
                listBox1.SelectedIndex = e.Y / listBox1.ItemHeight;
            }
            else
            {
                //Out of rang
            }
        }
    }

我不太懂C#,但我尝试了一下 :)


0
我也遇到了同样的问题。根据Hans Passant的回复,我稍微调整了一下代码,得到了下面的代码。我还发现,我根本不需要在那里放置contextMenuStrip1.Show(listBox1, e.Location);。它会自动为我调用。
(我正在使用Visual Studio 2010 Ultimate,并在.NET 4上编译。我还验证了下面的代码对于MouseUp和MouseDown都有效。)
    private void OnMouseDown(object sender, MouseEventArgs args)
    {
        if (args.Button == MouseButtons.Right)
        {
            var item = this.IndexFromPoint(args.Location);
            if (item >= 0 && this.SelectedIndices.Contains(item) == false)
            {
                this.SelectedItems.Clear();
                this.SelectedIndex = item;
            }
        }
    }

0
每个控件都从Control类继承了ContextMenu属性。将您的上下文菜单对象分配给列表框控件的ContextMenu属性,WinForms会自动处理它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接