通过在C#中使用鼠标拖动控件来移动控件

我试图通过拖动它来移动名为pictureBox1的控件。 问题是,当它移动时,它会一直从一个位置移动到鼠标周围的另一个位置,但它确实跟着它…这是我的代码。 如果你能帮助我,我真的很感激

public partial class Form1 : Form { public Form1() { InitializeComponent(); } bool selected = false; private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { selected = true; } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (selected == true) { pictureBox1.Location = e.Location; } } private void pictureBox1_MouseUp(object sender, MouseEventArgs e) { selected = false; } } 

一切你需要的:

 public partial class Form1 : Form { public Form1() { InitializeComponent(); } private Point MouseDownLocation; private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { MouseDownLocation = e.Location; } } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { pictureBox1.Left = eX + pictureBox1.Left - MouseDownLocation.X; pictureBox1.Top = eY + pictureBox1.Top - MouseDownLocation.Y; } } } 

尝试使用鼠标在运行时移动pictureBox控件

  private void pictureBox7_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { if (e.Button == MouseButtons.Left) { xPos = eX; yPos = eY; } } private void pictureBox7_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { PictureBox p = sender as PictureBox; if (p != null) { if (e.Button == MouseButtons.Left) { p.Top += (eY - yPos); p.Left += (eX - xPos); } } }