Search code examples
c#winformstreeviewnodescontextmenustrip

TreeNode click vs TreeView click


I have a TreeView and I need two things.

  • A Right-Click support if I click on a specific node.
  • A Right-Click support if I click anywhere else on the tree (where there is no nodes).

The two options would both give me a different ContextMenuStrip.
My two program now supports both type of clicks like this.

Specific Node click :

var someNode = e.Node.Tag as SomeNode;
if (someNode != null)
{
   someContextMenu.Show(someTree, e.Location);
   return;
}

Anywhere on the tree click :

enter image description here

The problem is that the Anywhere on the tree click event will fire before checking if I clicked on the node or on a blank spot from the TreeView.
Any Idea how I could change that behaviour ?


Solution

  • Assuming you are asking about winforms.

    You can use the TreeView.HitTest method which return a TreeViewHitTestInfo where you can know if you hit a node or not.