1 public Form1() 2 { 3 InitializeComponent(); 4 treeView1.AllowDrop = true; 5 treeView1.ItemDrag += new ItemDragEventHandler(treeView1_ItemDrag); 6 treeView1.DragEnter += new DragEventHandler(treeView1_DragEnter); 7 treeView1.DragDrop += new DragEventHandler(treeView1_DragDrop); 8 } 9 void treeView1_DragDrop(object sender, DragEventArgs e) 10 { 11 TreeNode moveNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode"); 12 //根据鼠标坐标确定要移动到的目标节点 13 Point pt; 14 TreeNode targeNode; 15 pt = ((TreeView)(sender)).PointToClient(new Point(e.X, e.Y)); 16 targeNode = this.treeView1.GetNodeAt(pt); 17 //如果目标节点无子节点则添加为同级节点,反之添加到下级节点的未端 18 TreeNode NewMoveNode = (TreeNode)moveNode.Clone(); 19 if (targeNode.Nodes.Count == 0) 20 { 21 targeNode.Parent.Nodes.Insert(targeNode.Index, NewMoveNode); 22 } 23 else 24 { 25 targeNode.Nodes.Insert(targeNode.Nodes.Count, NewMoveNode); 26 } 27 //更新当前拖动的节点选择 28 treeView1.SelectedNode = NewMoveNode; 29 //展开目标节点,便于显示拖放效果 30 targeNode.Expand(); 31 //移除拖放的节点 32 moveNode.Remove(); 33 } 34 void treeView1_DragEnter(object sender, DragEventArgs e) 35 { 36 if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode")) 37 { 38 e.Effect = DragDropEffects.Move; 39 } 40 else 41 { 42 e.Effect = DragDropEffects.None; 43 } 44 } 45 void treeView1_ItemDrag(object sender, ItemDragEventArgs e) 46 { 47 if (e.Button == MouseButtons.Left) 48 { 49 DoDragDrop(e.Item, DragDropEffects.Move); 50 } 51 }