zack
zack

Reputation: 7385

TreeNode Right Click Option

I am working TreeView and TreeView.Nodes in my C# GUI application and want to use the right click functionality on a few nodes in my tree. I have searched quite a bit but it seems like the SelectedNode is valid only for left click and there is nothing to capture the right click on a node. I want to add functionalities like 'Add', 'Remove', 'Rename', etc. to the nodes when right clicked upon. Any guidance please?

Thanks, Viren

Upvotes: 6

Views: 13983

Answers (2)

Jon Seigel
Jon Seigel

Reputation: 12401

Use the ContextMenuStrip property on the TreeView to add a context menu. If you need to not show the menu for some of the nodes, you can handle the ContextMenuStrip's Opening event to cancel it from showing itself -- or, you can disable some of the menu's options from there as well.

Edit: to grab the node under the mouse, handle the MouseUp event on the TreeView, and use this code:

TreeNode nodeUnderMouse = tvMyTreeView.GetNodeAt(e.X, e.Y);

Upvotes: 0

Scott Langham
Scott Langham

Reputation: 60421

Add a handler for MouseUp. In the handler, check the args for a right mouse button, return if it's not. Call treeView.GetNodeAt() with the mouse coordinates to find the node. Create a context menu.

Here's something similar for a list control which can be adapted for a TreeView:

        private void listJobs_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                int index = listJobs.IndexFromPoint(e.Location);
                if (index != ListBox.NoMatches)
                {
                    listJobs.SelectedIndex = index;

                    Job job = (Job)listJobs.Items[index];

                    ContextMenu cm = new ContextMenu();


                    AddMenuItem(cm, "Run", QueueForRun, job).Enabled = !job.Pending;
                    AddMenuItem(cm, "Cancel run", CancelQueueForRun, job).Enabled = (job.State == JobState.Pending || job.State == JobState.Running);
                    AddMenuItem(cm, "Open folder", OpenFolder, job);

                    cm.Show(listJobs, e.Location);
                }
            }
        }

        private MenuItem AddMenuItem(ContextMenu cm, string text, EventHandler handler,     object context)
        {
            MenuItem item = new MenuItem(text, handler);
            item.Tag = context;
            cm.MenuItems.Add(item);
            return item;
        }

You may need to use PointToClient or PointToScreen on the form to translate the coordinates appropriately. You'll soon realize if you need them when the context menu appears in the wrong place.

Upvotes: 8

Related Questions