c# 利用 两个TREEVIEW控件完成TEENODE的鼠标拖动操作

功能说明:

  我们有两个TREEVIEW控件——TREEVIEW1,TREEVIEW2。Treeview1内有三个NODE,Treeview2内有三个NODE。将Treeview1内的NODE拖动到Treeview2内,成为treeview2 NODE的子节点。

功能实现:

1:创建中间变量。

  Point myPoint = new Point();//记录鼠标尾随坐标

  TreeNode node;//记录要拖动的treeview1内的NODE

  添加Button Button1 控件实现treenode鼠标拖动尾随显示

2:添加FORM,TREEVIEW1,TREEVIEW2的鼠标MOVE动作,treeview1的鼠标DOWN动作,treeview2的鼠标UP动作。

  

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point myPosition = Control.MousePosition;
myPosition.Offset(myPoint.X - this.DesktopLocation.X, myPoint.Y - this.DesktopLocation.Y - 20);
button1.Location = myPosition;//this.DesktopLocation = myPosition;
}
}

private void treeView1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point myPosition = Control.MousePosition;
myPosition.Offset(myPoint.X - this.DesktopLocation.X, myPoint.Y - this.DesktopLocation.Y);
button1.Location = myPosition;//this.DesktopLocation = myPosition;
}
}

private void treeView2_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point myPosition = Control.MousePosition;
myPosition.Offset(myPoint.X - this.DesktopLocation.X, myPoint.Y - this.DesktopLocation.Y+20);
//button1.Location = myPosition;//this.DesktopLocation = myPosition;
int x=myPosition.X-treeView2.Location.X, y=myPosition.Y-treeView2.Location.Y;
foreach(TreeNode node in treeView2.Nodes)
{
if(e.Y>node.Bounds.Y && e.Y<node.Bounds.Y+node.Bounds.Height-1)
{
node.Checked = true;
button1.Text = node.Text;
break;
}
}
label1.Text = x.ToString();
label2.Text = y.ToString();
label3.Text = e.X.ToString();
label4.Text = e.Y.ToString();
}
}

private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
myPoint = new Point(-e.X, -e.Y);
int x = -e.X - this.DesktopLocation.X - treeView1.Location.X, y = -e.Y - this.DesktopLocation.Y - treeView1.Location.Y;
foreach (TreeNode node in treeView1.Nodes)
{
if (e.Y > node.Bounds.Y && e.Y < node.Bounds.Y + node.Bounds.Height - 1)
{
this.node = new TreeNode();
this.node.Text=node.Text;
this.node.Name = node.Name;
button1.Text = this.node.Text;
break;
}
}
}

private void treeView2_MouseUp(object sender, MouseEventArgs e)
{
Point myPosition = Control.MousePosition;
myPosition.Offset(myPoint.X - this.DesktopLocation.X, myPoint.Y - this.DesktopLocation.Y);
button1.Location = myPosition;//this.DesktopLocation = myPosition;
int x = myPosition.X - treeView2.Location.X, y = myPosition.Y - treeView2.Location.Y;
foreach (TreeNode node in treeView2.Nodes)
{
if (e.Y > node.Bounds.Y && e.Y < node.Bounds.Y + node.Bounds.Height - 1)
{
node.Checked = true;
node.Nodes.Add(this.node);
break;
}
}
}

原文地址:https://www.cnblogs.com/Roxlin/p/5307673.html