2013-05-05 100 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); 
       } 
      } 

     }