首页 > 代码库 > WinForm中TreeView控件实现鼠标拖动节点(可实现同级节点位置互换,或拖到目标子节点)

WinForm中TreeView控件实现鼠标拖动节点(可实现同级节点位置互换,或拖到目标子节点)

        private int draptype=1;//1:不同级,   不为1:拖同级
  private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                DoDragDrop(e.Item, DragDropEffects.Move);
            }
        }

        private void treeView1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(TreeNode)))
                e.Effect = DragDropEffects.Move;
            else
                e.Effect = DragDropEffects.None;
        }
     
        private void treeView1_DragDrop(object sender, DragEventArgs e)
        {
            //获得拖放中的节点
            TreeNode moveNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");
            //根据鼠标坐标确定要移动到的目标节点
            Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
            TreeNode targetNode = treeView1.GetNodeAt(pt);
            //如果目标节点为分组则添加到下级节点的未端,如果目标节点为素材文件则添加为同级节点
            TreeNode NewMoveNode = (TreeNode)moveNode.Clone();
            if (draptype == 1)
            {
                targetNode.Nodes.Insert(targetNode.Nodes.Count, NewMoveNode);

            }
            else
            {
                if (moveNode.NextNode == targetNode)
                {
                    targetNode.Parent.Nodes.Insert(targetNode.Index + 1, NewMoveNode);
                }
                else
                {
                    targetNode.Parent.Nodes.Insert(targetNode.Index, NewMoveNode);
                }
            }
            //更新当前拖动的节点选择
            treeView1.SelectedNode = NewMoveNode;
            //展开目标节点,便于显示拖放效果
            targetNode.Expand();

            //移除拖放的节点
            moveNode.Remove();
         
        }

 

WinForm中TreeView控件实现鼠标拖动节点(可实现同级节点位置互换,或拖到目标子节点)