结构体 Point 中方法Subtract()和Add()可用于在同一个坐标系中2点之间相对位置的计算:
public static Point Subtract(
Point pt,
Size sz
)
public static Point Add(
Point pt,
Size sz
)
而 Size 可以通过 Point 转换, 如下Size的一个构造函数:
public Size(
Point pt
)
下面以处于同一容器下(Form1)的2个组件 label1, label2 , 当拖曳第一个组件label1时, label2也同时跟着移动.
1. 定义全局字段:
private Point label1StartPos, offsetPoint;
private bool canMove = false;
2. 相关事件方法:
private void label1_MouseDown(object sender, MouseEventArgs e)
{
canMove = true;
label1StartPos = e.Location;
offsetPoint = Point.Subtract(label2.Location, new Size(label1.Location));
}
private void label1_MouseUp(object sender, MouseEventArgs e)
{
canMove = false;
}
private void label1_MouseMove(object sender, MouseEventArgs e)
{
if (canMove)
{
label1.Location = this.PointToClient(Point.Subtract(label1.PointToScreen(e.Location), new Size(label1StartPos)));
label2.Location = Point.Add(label1.Location, new Size(offsetPoint));
}
}
即可.