1 public Form1() 2 { 3 InitializeComponent(); 4 treeView1.AllowDrop = true; 5 treeView1.ItemDrag += new ItemDragEventHandler(treeView1_ItemDrag); 6 tr... ...
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 }