2014-11-22 16 views
0

我嘗試在c#中做一個程序,你試着裝飾一棵聖誕樹,我想用鼠標選擇全球並放在聖誕樹上。我可以做到這一點,但只爲一個picturebox,當我編寫第二個picturebox的代碼後,我運行全球移動中的程序。 這是我的代碼。如何解決這個問題?
P.S. picturebox1和2是地球儀,pb_brad是聖誕樹。C#我該如何移動一個帶有鼠標的圖片盒

public partial class Form1 : Form 
{ 
    Point location = Point.Empty; 
    public Form1() 
    { 
     InitializeComponent(); 
     pictureBox1.Parent = pb_brad; 
     pictureBox1.BackColor = Color.Transparent; 
     pictureBox2.Parent = pb_brad; 
     pictureBox2.BackColor = Color.Transparent; 

    } 

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e) 
    { 
     if (e.Button == MouseButtons.Left) 
     { 
      location = new Point(e.X, e.Y); 
     } 
    } 

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e) 
    { 
     if (location != Point.Empty) 
     { 
      Point newlocation = this.pictureBox1.Location; 
      newlocation.X += e.X - location.X; 
      newlocation.Y += e.Y - location.Y; 
      this.pictureBox1.Location = newlocation; 
     } 
    } 

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e) 
    { 
     location = Point.Empty; 
    } 

    private void pictureBox2_MouseDown(object sender, MouseEventArgs e) 
    { 
     if (e.Button == MouseButtons.Left) 
     { 
      location = new Point(e.X, e.Y); 
     } 
    } 

    private void pictureBox2_MouseMove(object sender, MouseEventArgs e) 
    { 
     if (location != Point.Empty) 
     { 
      Point newlocation = this.pictureBox1.Location; 
      newlocation.X += e.X - location.X; 
      newlocation.Y += e.Y - location.Y; 
      this.pictureBox2.Location = newlocation; 
     } 
    } 

    private void pictureBox2_MouseUp(object sender, MouseEventArgs e) 
    { 
     location = Point.Empty; 
    } 

} 
+1

define slomotion – Steve 2014-11-22 20:58:54

回答

0

我看到您在pictureBox2的MouseMove事件處理程序中使用pictureBox1。

順便說一句,我看到這兩個PictureBoxes處理程序是相同的。爲什麼不對所有PictureBox使用相同的處理程序,並通過sender參數獲取當前的PictureBox?

+0

我是一個初學者,我不知道如何做到這一點...你可以把代碼? – Siespi 2014-11-22 20:59:51

+0

@Joey作爲一個初學者,你應該總是試着自己先做,如果你不能在10-20分鐘內搞清楚然後再問一次 – Steve 2014-11-22 21:00:43

+0

我發現了這些文章:http://stackoverflow.com/questions/14479143/what-use-object-sender-eventargs-e-parameters-give and http://stackoverflow.com/questions/1530867/understanding-c-sharp-events-use-of-sender-object提供了一些示例。順便說一句,在pictureBox2_MouseMove中更改pictureBox1到pictureBox2解決了這個問題? – 2014-11-22 21:02:55