如何从ContextMenuStrip右键单击项目?

时间:2013-12-09 15:25:23

标签: c# picturebox contextmenustrip

我有一个PictureBox。

如果我右键单击PictureBox,我的ContextMenuStrip(右键菜单)就会出现。

在那个ContextMenuStrip中是一个ToolStripMenuItem(右键菜单中的一个选项)。

ToolStripMenuItem上有一个事件可以处理在单击该选项时会发生什么。


我们从ToolStripMenuItem的“Clicked”功能开始。我需要以某种方式以编程方式返回PictureBox。从那里,我可以修改PictureBox。

ToolStripMenuItem - > ContextMenuStrip - >图片框

我该怎么做?

3 个答案:

答案 0 :(得分:1)

如果菜单项的click事件处理程序名为OnToolStripMenuItemClick,则以下内容可能是解决您问题的方法:

private void OnToolStripMenuItemClick(object sender, EventArgs e)
{
    var menuItem = sender as ToolStripMenuItem;
    var contextMenu = menuItem.Parent as ContextMenuStrip;
    var pictureBox = contextMenu.SourceControl;
}

当然,转换后使用null访问媒体资源时,请不要忘记检查as

答案 1 :(得分:0)

我不确定我是否真的理解你的问题,但我想你想让用户在想要通过点击右键取消当前操作时返回到图片框。在这种情况下,您不应该在click事件中实现您的工作,因为右键和左键都可以触发click事件,相反,您应该在“MouseUp”事件中处理您的工作,如下所示:

private void menuItemBack_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            MessageBox.Show("back item is clicked");
        }
        else
        {
            MessageBox.Show("I will come back.");
            //do your return things here.
        }
    }

答案 2 :(得分:0)

我刚刚在C#中遇到了同样的问题,值的路径似乎是这样的:

sender.Owner.SourceControl;

但是,由于senderOwner等都是泛型类,因此我必须将所有内容强制转换如下:

PictureBox pb = (PictureBox) ((ContextMenuStrip)((ToolStripMenuItem)sender).Owner).SourceControl;

丑陋,但是可行。