gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:59:04 26 4
gpt4 key购买 nike

我正在我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com