C# 图片框跟随鼠标移动
先贴上代码
private bool isMouseDown = false;
private Point mouseOffset; //记录鼠标指针的坐标
private void PicBox_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseOffset.X = e.X;
mouseOffset.Y = e.Y;
isMouseDown = true;
}
}
private void PicBox_MouseMove(object sender, MouseEventArgs e)
{
if (isMouseDown)
{
int left = PicBox.Left + e.X - mouseOffset.X;
int top = PicBox.Top + e.Y - mouseOffset.Y;
PicBox.Location = new Point(left,top);
}
}
private void PicBox_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isMouseDown = false;
}
}
事件中的 MouseEventArgs e :
根据e得到的坐标,不是鼠标相对与Form左上角的坐标,而是相对于图片框的左上角坐标,所以算鼠标偏移量的时候,只要计算两次事件对象e中的坐标的差值!
保存鼠标按下时相对于图片框左上角的坐标
mouseOffset.X = e.X;
mouseOffset.Y = e.Y;
移动时得到偏移量
e.X - mouseOffset.X;
e.Y - mouseOffset.Y;
算出图片框的新位置
int left = PicBox.Left + e.X - mouseOffset.X;
int top = PicBox.Top + e.Y - mouseOffset.Y;