C#如何通过右键单击选择ListBox项?

时间:2012-02-10 14:08:55

标签: c# winforms listbox selection

我已经为此尝试了很多方法并完成了数小时的研究,但它似乎从来没有对我有用。

这是我目前的代码,我不知道它为什么不起作用。

    private void listBox1_MouseDown(object sender, MouseEventArgs e)
    {
        listBox1.SelectedIndex = listBox1.IndexFromPoint(e.X, e.Y);
        if (e.Button == MouseButtons.Right)
        {
            contextMenuStrip1.Show();
        }
    }

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

任何想法?

5 个答案:

答案 0 :(得分:7)

你很近,你忘了选择项目。修正:

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

答案 1 :(得分: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)
            }
        }
    }

答案 2 :(得分:0)

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

答案 3 :(得分: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#不太了解,但我尝试过:)

答案 4 :(得分:0)

我正在处理同样的问题。从Hans Passant的回复中我稍微调整了一下以获得以下代码。我还发现我根本不需要将contextMenuStrip1.Show(listBox1, e.Location);放在那里。它自动被我召唤。

(我在.NET 4中使用Visual Studio 2010 Ultimate和编译。我还验证了以下代码适用于BOTH 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;
            }
        }
    }
相关问题