gpt4 book ai didi

c# - 将完整的 TreeView 设置为剪贴板

转载 作者:太空狗 更新时间:2023-10-30 01:29:14 28 4
gpt4 key购买 nike

我正在使用 Windows 窗体,我想复制整个 TreeView 及其 subview ,以便在 KeyDown 事件中的剪贴板中设置

首先我尝试将父节点设置为:

  private void tvProjectList_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == (Keys.C))
{
var treeViewParents = "";
foreach (TreeNode tn in tvProjectList.Nodes)
{
treeViewParents += tn.Text + Environment.NewLine;
}
Clipboard.SetText(treeViewParents);

}
}

但它只是获取一个节点而不是所有节点。我应该怎么做?问候

更新:

为了得到节点和他们的 child ,我有

   private void tvProjectList_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == (Keys.C))
{

foreach (TreeNode node in tvProjectList.Nodes)
{
PrintNodesRecursive(node);
}
}
}



public void PrintNodesRecursive(TreeNode oParentNode)
{
Console.WriteLine(oParentNode.Text);

var treeViewParents = "";
StringBuilder sb = new StringBuilder();

// Start recursion on all subnodes.
foreach (TreeNode oSubNode in oParentNode.Nodes)
{
sb.Append(oSubNode.Text + Environment.NewLine);
PrintNodesRecursive(oSubNode);
}
Clipboard.SetText(sb.ToString());

}

但是字符串生成器总是带有空字符串...为什么数据没有保存在字符串生成器中?问候

最佳答案

扩展我的评论,这里有一个实现递归方法的示例实现:

private void CopyTreeViewToClipboard(TreeView treeView)
{
// Make a StringBuilder to store the text of each individual node
var treeViewStringBuilder = new StringBuilder();

// Initiate the recursive method
GetTreeViewNodesText(treeView.Nodes, treeViewStringBuilder);

// because StringBuilder is a reference type we do not need use a return value
// and we can copy to clipboard using the already existing reference
Clipboard.SetText(treeViewStringBuilder.ToString());
}

private void GetTreeViewNodesText(TreeNodeCollection nodesInCurrentLevel, StringBuilder sb, int level = 0)
{
foreach (TreeNode currentNode in nodesInCurrentLevel)
{
// Add some padding (spaces) in front to display the current level
sb.Append(new string(' ', level * 2));
// Add the text and terminate the line \n\r
sb.AppendLine(currentNode.Text);

// Recursion happens here, it's level + 1 instead of level++ because we
// do not want to alter the level for the next nodes in nodesInCurrentLevel
GetTreeViewNodesText(currentNode.Nodes, sb, level + 1);
}
}

关于c# - 将完整的 TreeView 设置为剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53399832/

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