1

我有这个选定的索引事件 a ListBox

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{    
    if (listBox1.SelectedItem != null)
    {
        label4.Text = listBox1.SelectedItem.ToString();
        string startTag = "Url: ";
        string endTag = " ---";
        int startTagWidth = startTag.Length;
        int endTagWidth = endTag.Length;
        int index = 0;
        index = label4.Text.IndexOf(startTag, index);
        int start = index + startTagWidth;
        index = label4.Text.IndexOf(endTag, start + 1);
        string g = label4.Text.Substring(start, index - start);
        label4.Text = g;
        mainUrl = g;
    }
}

我希望在我选择一个索引(项目)之后ListBox,我现在用鼠标右键单击这个索引,它会做一些事情。但是,如果我在表单上的任何其他区域上单击鼠标右键,ListBox它不会做任何事情。仅当鼠标位于所选索引上时。

我需要做的是,用户将能够从ListBox. 我只是不知道当用户单击鼠标右键时如何做到这一点的最佳逻辑是什么。

显示我在用户第一次选择一个项目时并且仅当鼠标在该选定项目上方/上时才成功?显示我这样做,如果用户在任何项目上单击鼠标右键,它将自动选择它并执行某些操作?

我不确定哪种方式更好,逻辑以及如何去做。

4

1 回答 1

2

只需订阅Listbox的MouseDown,IndexFromPoint用于检查当前点击的项是否为选中项。

这是一个例子:

private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
        if (e.Button == System.Windows.Forms.MouseButtons.Right)
        {
            int index = listBox1.IndexFromPoint(e.Location);
            {
                if (index == listBox1.SelectedIndex)
                {
                    MessageBox.Show("Selected item clicked");
                }
            }
        }
}
于 2013-02-16T12:11:47.670 回答