Get the SourceControl of a DropDownMenu

The ContextMenuStrip SourceControl (the reference of the current Control where the Context Menu is activated) can be retrieved, from a ToolStripMenuItem, inspecting the OwnerItem reference and moving upstream until the OwnerItem reference is null, then inspecting the Owner value, which references the ContextMenuStrip.
(Unfortunately, the SourceControl reference is only available in the ContextMenuStrip control).

A simple alternative method is using a Field that references the Control where the current ContextMenuStrip has been activated (you can have just one active ContextMenuStrip).
This Field reference, set when the ContextMenuStrip is opened – by subscribing to the Opened() event – can then be accessed by any of the ToolStripMenuItem.
The Field reference is then set back to null when then ContextMenuStrip is closed.

▶ Dispose of the contextMenuOwner object when the Form closes.

An example:
(toolStripMenuItem is a generic name, it must be set to an actual control name).

Control contextMenuOwner = null;

private void toolStripMenuItem_Click(object sender, EventArgs e)
{
    contextMenuOwner?.BackColor = Color.Blue;
    //(...)
}

private void contextMenuStrip1_Opened(object sender, EventArgs e)
{
    contextMenuOwner = (sender as ContextMenuStrip).SourceControl;
}

private void contextMenuStrip1_Closed(object sender, ToolStripDropDownClosedEventArgs e)
{
    contextMenuOwner = null;
}

Leave a Comment