确定从ToolStripMenuItem鼠标单击哪个PictureBox

时间:2013-11-11 17:02:50

标签: c# winforms

我有一些动态创建的PictureBox和一个ContextMenuToolStripMenuItem名为“删除”...我只想删除点击的PictureBoxContextMenu附加了PictureBox个。{/ p>

怎么做?请解释因为我还是初学者。

1 个答案:

答案 0 :(得分:3)

您需要关注菜单所有者链,直到您获得控件:

private void RemoveMenuItem_Click(object sender, EventArgs e) {
  ToolStripMenuItem ti = sender as ToolStripMenuItem;
  ContextMenuStrip cs = ti.Owner as ContextMenuStrip;
  PictureBox pb = cs.SourceControl as PictureBox;
  MessageBox.Show(pb.Name);  // or pb.Dispose();
}

此代码未执行任何错误检查。在尝试访问其任何属性之前,您应该检查这些变量中是否有任何变量。

Cody Gray在这里给出了一个全面的答案:Determine what control the ContextMenuStrip was used on