using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//保存前一个鼠标进入的节点
private TreeNode MyOldNode;
private void Form1_Load_1(object sender, EventArgs e)
{
//添加树形视图子节点
this.treeView1.Nodes.AddRange(
new TreeNode[]
{
new TreeNode("中国直辖市", new TreeNode[]
{
new TreeNode("北京市", new TreeNode[]
{
new TreeNode("东城区"), new TreeNode("西城区"),new TreeNode("朝阳区")
}),
new TreeNode("上海市", new TreeNode[]
{
new TreeNode("长宁区"),new TreeNode("黄埔区"), new TreeNode("浦东区")
}),
new TreeNode("重庆市", new TreeNode[]
{
new TreeNode("长寿区", new TreeNode[]
{
new TreeNode("云台镇"),
new TreeNode("凤城镇", new TreeNode[]
{
new TreeNode("黄桷湾"),new TreeNode("关口")
})
}),
new TreeNode("渝北区"),new TreeNode("北碚区")
})
})
});
this.treeView1.AllowDrop = true;
this.treeView1.ExpandAll();
}
private void treeView1_DragEnter_1(object sender, DragEventArgs e)
{
//处理 treeView1控件DragEnter事件
//获取节点的数据内容
object MyData = e.Data.GetData(typeof(TreeNode));
//如果节点有数据,拖放目标允许移动
if (MyData != null)
{
e.Effect = DragDropEffects.Move;
}
else
{
e.Effect = DragDropEffects.None;
}
TreeView MyTreeView = (TreeView)sender;
TreeNode MyNode = MyTreeView.GetNodeAt(treeView1.PointToClient(new Point(e.X, e.Y)));
if (MyNode != null)
{
//改变进入节点的背景色
MyNode.BackColor = Color.Blue;
//保存此节点,进入下一个时还原背景色
MyOldNode = MyNode;
}
}
private void treeView1_DragOver_1(object sender, DragEventArgs e)
{
//处理 treeView1控件DragOver事件
//修改鼠标进入节点的背景色,还原上一个节点的背景色
TreeView MyTreeView = (TreeView)sender;
TreeNode MyNode = MyTreeView.GetNodeAt(treeView1.PointToClient(new Point(e.X, e.Y)));
if ((MyNode != null) && (MyNode != MyOldNode))
{
MyOldNode.BackColor = Color.White;
MyNode.BackColor = Color.Blue;
MyOldNode = MyNode;
}
}
private void treeView1_DragDrop_1(object sender, DragEventArgs e)
{
//处理 treeView1控件DragDrop事件
TreeNode MyNode = (TreeNode)e.Data.GetData(typeof(TreeNode));
TreeView MyTreeView = (TreeView)sender;
//得到当前鼠标进入的节点
TreeNode MyTargetNode = MyTreeView.GetNodeAt(treeView1.PointToClient(new Point(e.X, e.Y)));
if (MyTargetNode != null)
{
TreeNode MyTargetParent = MyTargetNode.Parent;
//删除拖放的节点
MyNode.Remove();
//添加到目标节点
MyTargetNode.Nodes.Add(MyNode);
MyTargetNode.BackColor = Color.White;
MyTreeView.SelectedNode = MyTargetNode;
}
}
private void treeView1_ItemDrag_1(object sender, ItemDragEventArgs e)
{
//处理 treeView1控件ItemDrag事件
//设置拖放类型为移动
DoDragDrop(e.Item, DragDropEffects.Move);
}
}
}