Search This Blog

Wednesday, October 16, 2013

Determine control ToolStripItem was clicked on

C# > Controls > ContextMenuStrip


Scenario:
We have many labels on forms and one ContextMenuStrip. How can we find the control which was clicked?

Solution:

private void copyToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ToolStripItem menuItem = sender as ToolStripItem;
            if (menuItem != null)
            {
                ContextMenuStrip owner = menuItem.Owner as ContextMenuStrip;
                if (owner != null)
                {
                    Control sourceControl = owner.SourceControl;
                    Label lbl = sourceControl as Label;
                }
            }
        }