c# - TreeNode 右键单击​​选项

标签 c# winforms tree-nodes

我正在我的 C# GUI 应用程序中使用 TreeView 和 TreeView.Nodes,并希望在我的树中的几个节点上使用右键单击功能。我已经搜索了很多,但似乎 SelectedNode 仅对左键单击有效,并且没有任何内容可以捕获节点上的右键单击。我想在右键单击时向节点添加“添加”、“删除”、“重命名”等功能。有什么指导吗?

谢谢, 维伦

最佳答案

为 MouseUp 添加处理程序。 在处理程序中,检查鼠标右键的参数,如果不是则返回。 使用鼠标坐标调用 treeView.GetNodeAt() 以查找节点。 创建上下文菜单。

这里有一些类似于列表控件的内容,可以适用于 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;
        }

您可能需要在表单上使用 PointToClient 或 PointToScreen 来适本地转换坐标。当上下文菜单出现在错误的位置时,您很快就会意识到是否需要它们。

关于c# - TreeNode 右键单击​​选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1444492/

相关文章:

c# - 如何使用 Coded-UI 显式使测试用例失败

C# 无法从父类访问 Form 的公共(public)成员

c# - 如何在 Windows.Forms 中制作 float (工具提示)控件?

java - 从 JTree 添加和删除节点

c# - 是否可以在javascript函数中将变量作为参数传递?

c# - 在 C# 中解码没有 schema 的 protobuf

c# - 检查字符串输入的内容

c# - 使用 C# 中的 StackExchange/Sentinel 进行 Redis 故障转移

.net - 如何将两个组合框的所选项目与单个DataSource分开?

c - C 中的链表