此代码位于form1构造函数中:
ContextMenu cm = new ContextMenu();
cm.MenuItems.Add("Save Rectangle");
cm.MenuItems.Add("Reset Rectangle");
cm.MenuItems.Add("View Rectangle Information");
listBoxSnap.ContextMenu = cm;
现在它做的是,我在ListBox中右键单击的任何项目或区域,它将显示菜单。但我希望只有当我右键单击我现在所选的项目时才会右键单击并显示菜单。当我运行程序时,会自动选择第一个项目:
if (this.listBoxSnap.Items.Count > 0)
this.listBoxSnap.SetSelected(0, true);
listBoxSnap.Select();
我希望如果我单击鼠标左键选择另一个项目,或者向上移动键以选择项目,则只有该项目的菜单右键单击可用(启用)。如果我右键单击listBox中的任何其他区域,则不显示菜单。
仅当我将鼠标光标放在当前所选项目上时才显示菜单。
与在Windows中标记文本并右键单击它时相同,它会显示一个菜单,如果我右键单击未标记的其他文本,它将显示一个不同的菜单。
编辑:
这很有效。
在form1的顶部:
ContextMenu cm;
在form1构造函数中:
cm = new ContextMenu();
cm.MenuItems.Add("Save Rectangle");
cm.MenuItems.Add("Reset Rectangle");
cm.MenuItems.Add("View Rectangle Information");
listBox鼠标按下事件:
private void listBoxSnap_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
var item = listBoxSnap.IndexFromPoint(e.Location);
if (item >= 0)
{
listBoxSnap.SelectedIndex = item;
cm.Show(listBoxSnap, e.Location);
}
}
}
答案 0 :(得分:0)
试试这个
private void listBoxSnap_MouseUp(object sender, MouseEventArgs e)
{
if (listBoxSnap.SelectedIndex == -1 || e.Button != MouseButtons.Right)
return;
Rectangle r = listBoxSnap.GetItemRectangle(listBoxSnap.SelectedIndex);
if (r.Contains(e.Location))
{
cm.Show(listBoxSnap, e.Location);
}
}