这是代码。 在Form1加载事件:
private void Form1_Load(object sender, EventArgs e)
{
if (listBox1.Items != null && listBox1.Items.Count > 0)
{
listBox1.Select();
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;
listboxContextMenu = new ContextMenuStrip();
listboxContextMenu.Opening += new CancelEventHandler(listboxContextMenu_Opening);
}
}
然后是listBox mouseDown事件:
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)
{
listboxContextMenu.Show();
}
}
}
}
然后是Opening事件:
private void listboxContextMenu_Opening(object sender, CancelEventArgs e)
{
//clear the menu and add custom items
listboxContextMenu.Items.Clear();
listboxContextMenu.Items.Add(string.Format("Edit - {0}", listBox1.SelectedItem.ToString()));
}
它的作用是当我点击鼠标右侧列表框中的特定项目时,它会显示contextMenu。
问题是contextMenu一直出现在屏幕左上角,而不是表格,而是屏幕左上角。
第二个问题是,仅在我第二次单击所选项目时才会显示“选项”菜单。 当我运行我的程序时,listBox中的第一项已被选中,但只有当我在项目上单击两次时,才会显示相应菜单。之后我每次点击一次,但第一次运行我的程序时,我需要点击右键单击两次。
如何解决这两个问题?
答案 0 :(得分:0)
使用MouseUp Event
代替MouseDown Event
private void listBox1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
int index = listBox1.IndexFromPoint(e.Location);
if (index == - 1) return;
listBox1.SelectedIndex = index;
listboxContextMenu.Show(listBox1, listBox1.PointToClient(System.Windows.Forms.Cursor.Position));
}
}