2013-05-05 65 views
9

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

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; 
    } 

} 

回答

26

所有你需要:

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 = e.X + pictureBox1.Left - MouseDownLocation.X; 
      pictureBox1.Top = e.Y + pictureBox1.Top - MouseDownLocation.Y; 
     } 
    } 

} 
+0

在运行时移动PictureBox控件@TurmDrummer你应该在本网站上使用英文(至少尝试)让其他用户了解你。相关讨论:http://meta.stackexchange.com/questions/118678/how-should-we-handle-wholly-non-english-comments – astef 2014-05-12 06:33:36

+0

对不起, 我没有意识到,我在德国写了我的评论。 有时候我不知道我在用哪种语言进行交流。 我的问题是, 因为你似乎对这种UI代码有很好的了解,你有一个想法,我怎样才能平滑拖动控件的运动一点点? 如果没有这种实施方式的实际解决方案,我宁愿坚持自己的努力,因为我发现的其他解决方案往往是不好的书面,有缺陷或不切实际的,您的解决方案现在正常工作。 – TurmDrummer 2014-05-21 14:31:00

+0

@TurmDrummer即使我对这方面有很好的了解(即使我不知道),并且即使我有关于你在问什么(我没有)的想法,为什么不创建一个新的问题? – astef 2014-05-21 14:59:57

2

尝试用小鼠

private void pictureBox7_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) 
     { 
      if (e.Button == MouseButtons.Left) 
      { 
       xPos = e.X; 
       yPos = e.Y; 
      } 
     } 

     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 += (e.Y - yPos); 
        p.Left += (e.X - xPos); 
       } 
      } 

     }