Reputation: 36546
In a C# winforms app, I've assigned the same contextual menu to four PictureBox controls.
I'd like to determine which was used to activate the contextual menu.
I did the following in the Click event for a given menu item, which seems awkward:
MenuItem_Click(object sender, EventArgs e)
{
PictureBox Origin = (PictureBox)sender;
switch (Origin.Name)
{
case "pbOne":
// do something with #1
break;
case "pbTwo":
// do something with #2
break;
}
}
Working with the control name is the part that feels awkward.
Can you suggest a better way?
Edit:
Casting sender
to a PictureBox does not work, as I forgot the menu item would be the sender, not the PictureBox. So I will have to further backtrack.
Upvotes: 1
Views: 727
Reputation: 57220
Simply use SourceControl
property:
var pictureBox = contextMenuStrip1.SourceControl as PictureBox;
Upvotes: 3
Reputation: 942368
Not so sure how you made that work. The sender is the menu item, not the picture box. If this actually works then you already have the reference to the picture box you want to tinker with. It's Origin. No need for the switch statement.
Another way that works is to use the Opening event:
private PictureBox currentBox;
private void allContextMenuStrips_Opening(object sender, CancelEventArgs e) {
currentBox = (sender as ContextMenuStrip).SourceControl as PictureBox;
}
And you can now use currentBox in any of the menu item Click event handlers. It works because there can be only one menu open at the same time.
Upvotes: 1