在我的项目中,我有一个ListView
,当我点击大图标中的右键时,我想打开ContextMenuStrip
。我尝试了很多东西,但我没有成功。当我在ListView
内右键单击时,ContextMenuStrip
会打开,但我希望看到我右键单击大图标时。
另外,我需要帮助获取点击图标的名称(属性)。
答案 0 :(得分:1)
这是一个快速而肮脏的解决方案;请把更多的工作投入到我的工作中。
// a class level reference, prepare it where you want..
ContextMenuStrip ms = new ContextMenuStrip();
您应该对MouseDown
或MouseUp
事件进行编码:
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();
}
答案 1 :(得分:0)
请你试试以下内容,看看它是否有效......
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);
}
}
}
答案 2 :(得分:0)
这应该有效
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);
}
}
}
在鼠标单击位置搜索listview项。如果它在那里,显示菜单.........