Вопрос

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 ?

Это было полезно?

Решение

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.

Другие советы

private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {
        TreeViewHitTestInfo info = treeView1.HitTest(e.Location);
        treeView1.SelectedNode = info.Node;

        if (info.Node == null)
        {
            contextMenuStrip1.Show(Cursor.Position);
        }
        else
        {
            contextMenuStrip2.Show(Cursor.Position);
        }
    }
}

Or the mouse up event depending on your needs. Also you can use GetNodeAt(e.Location) instead of the TreeViewHitTestInfo class.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top