This might be incredibly simple and I'm not seeing it because it's the end of a long day, and if it is I apologize in advance.
I've got a set of Buttons that when right-clicked pop up a ContextMenu. The menu has two MenuItems, both of which have a Click handler function assigned. I'm triggering the ContextMenu to pop up on the right click of a button like so:
Overly simplified example:
public void InitiailizeButtonContextMenu()
{
buttonContextMenu = new ContextMenu();
MenuItem foo = new MenuItem("foo");
foo.Click += OnFooClicked;
MenuItemCollection collection = new MenuItemCollection(buttonContextMenu);
collection.Add(foo);
}
public void OnButtonMouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
// left click stuff handling
if (e.Button == MouseButtons.Right)
buttonContextMenu.Show((Button)sender, new Point(e.X, e.Y));
}
public void OnFooClicked(object sender, EventArgs e)
{
// Need to get the Button the ContextMenu .Show'd on in
// OnButtonMouseClick... thoughts?
}
ContextMenu buttonContextMenu;
I need to be able to get the Button that triggered the ContextMenu to pop up IN the Click handler for the MenuItem, or get it to it somehow. MenuItem.Click takes EventArgs, so nothing useful there. I can cast object sender back to MenuItem but I can't find anything that tells me what made it pop up. Is this possible?
Use the ContextMenu.SourceControl property, it gives you a reference to the Button instance back.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With