Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# = MenuItem.Click handler - Get the object the context menu belongs to?

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?

like image 982
trycatch Avatar asked Dec 21 '22 15:12

trycatch


1 Answers

Use the ContextMenu.SourceControl property, it gives you a reference to the Button instance back.

like image 99
Hans Passant Avatar answered Dec 28 '22 06:12

Hans Passant