private TreeNode oldenterNode;
        private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            //启动拖放操作, 设置拖放类型为MOVE移动
            DoDragDrop(e.Item, DragDropEffects.Move);
        }

        //保存前一个鼠标进入的TreeNode
        private void treeView1_DragEnter(object sender, DragEventArgs e)
        {
            //获取TreeNode类型的数据内容.
            object data = e.Data.GetData(typeof(TreeNode));
            //如果有数据拖放时不允许旋转
            if (data != null)
            {
                e.Effect = DragDropEffects.Move;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
            //获得当前TreeView的引用
            TreeView theTree = (TreeView)sender;
            //得到鼠标进入TreeNode的引用
            TreeNode enterNode = theTree.GetNodeAt(treeView1.PointToClient(new Point (e.X, e.Y)));

            if (enterNode != null)
            {
                //改变进入TreeNode的背景色
                enterNode.BackColor = Color.Blue;
                //保存此TreeNode,进入下一个时还原背景色
                oldenterNode = enterNode;
            }
        }

        private void treeView1_DragOver(object sender, DragEventArgs e)
        {
            //修改鼠标进入TreeNode的背景色,还原上一个TreeNode背景色
            TreeView theTree = (TreeView)sender;
            TreeNode enterNode = theTree.GetNodeAt(treeView1.PointToClient(new Point(e.X, e.Y)));

            if ((enterNode != null) && (enterNode != oldenterNode))
            {
                oldenterNode.BackColor = Color.White;
                enterNode.BackColor = Color.Blue;
                oldenterNode = enterNode;
            }
        }

        private void treeView1_DragDrop(object sender, DragEventArgs e)
        {
            //得到拖放数据,并转换为TreeNode型
            TreeNode theNode = (TreeNode)e.Data.GetData(typeof(TreeNode));
            TreeView theTree = (TreeView)sender;

            //得到鼠标进入TreeNode,而拖放目标TreeNode
            TreeNode targetNode = theTree.GetNodeAt(treeView1.PointToClient(new Point(e.X, e.Y)));

            if (targetNode != null)
            {
                TreeNode targetParent = targetNode.Parent;
                //删除拖放的TreeNode
                theNode.Remove();
                //添加到目标TreeView下
                targetNode.Nodes.Add(theNode);
                targetNode.BackColor = Color.White;
                theTree.SelectedNode = targetNode;
            }
        }

Posted on 2008-08-22 14:59  Yongming Ye  阅读(732)  评论(0编辑  收藏  举报