How to get the item right clicked on from ContextMenuStrip?

5.6k views Asked by At

I have a PictureBox.

If I right click the PictureBox, my ContextMenuStrip (right click menu) appears.

In that ContextMenuStrip is a ToolStripMenuItem (one of the options in the right click menu).

There is an event on the ToolStripMenuItem that handles what happens if that option is clicked.


We're starting from ToolStripMenuItem's "Clicked" function. I need to somehow get back to the PictureBox programmatically. From there, I can modify the PictureBox.

ToolStripMenuItem -> ContextMenuStrip -> PictureBox

How would I go about this?

3

There are 3 answers

4
RePierre On BEST ANSWER

If the click event handler for your menu item is named OnToolStripMenuItemClick, the following might be an approach to your problem:

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

Of course, don't forget to check for null when accessing properties after conversion with as.

0
Scott Yang On

I'm not sure that I really understood your problem, but I guess you want to let users can return to the picturebox when they want to cancel current operation by clicking the right button. In this case, you should not implement your work in click event, because right and left button both can trigger the click event, instead, you should process your work in the event "MouseUp", like this:

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.
        }
    }
0
Guti On

I've just come across this same problem in C#, and the path to the value seems to be something like:

sender.Owner.SourceControl;

However, since sender, Owner and so on are generic classes, I had to cast everything as follows:

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

Ugly, but it works.