A Win Form ContextMenuStrip is a "Component" meant to be associated with an entire Control, or multiple Controls.
If you set the ContextMenuStrip Property of the TreeView to use the ContextMenuStrip you've added to the Form at design-time, then it's going to appear whenever you context-click
anywhere in the TreeView's DisplayRectangle bounds: that's
independent of any Node, or Nodes, being Selected.
If you wish to limit the display of the ContextMenu, here's an example that will only show it on context-click when the TreeNode you context-click on happens to be the SelectedNode of the TreeView:
private TreeNode currentRightClickedTreeNode;
private bool IsContextMenuHidden = false;
private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
IsContextMenuHidden = false;
if (e.Button == MouseButtons.Right)
{
currentRightClickedTreeNode = treeView1.GetNodeAt(e.Location);
IsContextMenuHidden = currentRightClickedTreeNode == null || currentRightClickedTreeNode != treeView1.SelectedNode;
}
}
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
e.Cancel = IsContextMenuHidden;
}
This works by testing for two conditions that determine whether or not the ContextMenu is shown:
1. does the context-click occur somewhere "outside" all TreeNodes
2. does the context-click occur on a TreeNode that is not selected