For a ContextMenu:
The problem is that the sender parameter points to the item on the context menu that was clicked, not the context menu itself.
It’s a simple fix, though, because each MenuItem exposes a GetContextMenu method that will tell you which ContextMenu contains that menu item.
Change your code to the following:
private void MenuViewDetails_Click(object sender, EventArgs e)
{
// Try to cast the sender to a MenuItem
MenuItem menuItem = sender as MenuItem;
if (menuItem != null)
{
// Retrieve the ContextMenu that contains this MenuItem
ContextMenu menu = menuItem.GetContextMenu();
// Get the control that is displaying this context menu
Control sourceControl = menu.SourceControl;
}
}
For a ContextMenuStrip:
It does change things slightly if you use a ContextMenuStrip instead of a ContextMenu. The two controls are not related to one another, and an instance of one cannot be casted to an instance of the other.
As before, the item that was clicked is still returned in the sender parameter, so you will have to determine the ContextMenuStrip that owns this individual menu item. You do that with the Owner property. Finally, you’ll use the SourceControl property to determine which control is displaying the context menu.
Modify your code like so:
private void MenuViewDetails_Click(object sender, EventArgs e)
{
// Try to cast the sender to a ToolStripItem
ToolStripItem menuItem = sender as ToolStripItem;
if (menuItem != null)
{
// Retrieve the ContextMenuStrip that owns this ToolStripItem
ContextMenuStrip owner = menuItem.Owner as ContextMenuStrip;
if (owner != null)
{
// Get the control that is displaying this context menu
Control sourceControl = owner.SourceControl;
}
}
}