问题
In my project I have a ListView
and I would like to open my ContextMenuStrip
when I clicked right button in the large icon. I tried many things but I am unsuccessful. When I right click inside of ListView
the ContextMenuStrip
opens, but I want to see just when I right clicked the large icon.
Also I need to help about get the clicked icon's name (properties).
回答1:
This is a quick and dirty solution; please do put more work into it than I did..
// a class level reference, prepare it where you want..
ContextMenuStrip ms = new ContextMenuStrip();
You should either code the MouseDown
or the MouseUp
event:
private void listView1_MouseDown(object sender, MouseEventArgs e)
{
// disassociate from listview at first:
listView1.ContextMenuStrip = null;
// check for right button
if (e.Button != System.Windows.Forms.MouseButtons.Right) return;
// get item info:
ListViewHitTestInfo hi = listView1.HitTest(e.Location);
// no item hit:
if (hi.Item == null) return;
// calculate the image rectangle:
// this contains the unscrolled y coordinate:
Point iloc = listView1.GetItemRect(hi.Item.Index).Location;
// we combine it with the x-position:
Rectangle r = new Rectangle(new Point (hi.Item.Position.X, iloc.Y),
imageList1.ImageSize);
// no image hit:
if ( !r.Contains(e.Location) ) return;
// maybe prepare or change the menue now..
// here I display the image name from the keys array:
ms.Items[0].Text = imageList1.Images.Keys[hi.Item.ImageIndex];
ms.Location = e.Location;
// associate with listview and show
listView1.ContextMenuStrip = ms;
ms.Show();
}
回答2:
Can you please try the following and let see wether it works or not...
private void listView1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
if (listView1.FocusedItem.Bounds.Contains(e.Location) == true)
{
contextMenuStrip1.Show(Cursor.Position);
}
}
}
回答3:
This should work
private void listView1_MouseClick(object sender, MouseEventArgs e)
{
ListView listView = sender as ListView;
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
ListViewItem item = listView.GetItemAt(e.X, e.Y);
if (item != null)
{
item.Selected = true;
contextMenuStrip1.Show(listView , e.Location);
}
}
}
Search the listview item on mouse click location. If it is there, show the menu.........
来源:https://stackoverflow.com/questions/32959874/listview-large-icon-right-click-to-open-contextmenustrip