2013-08-29 35 views
0

抱歉再次打擾與類似的問題。但是,我在C#中再次遇到了我的代碼問題。我想給你到目前爲止,我已經得到了代碼:C# - 拖放和保持控制:擴展

private void pictureBox2_Click(object sender, EventArgs e) 
    { 
     PictureBox flower2 = new PictureBox(); 
     flower2.Image = Properties.Resources.Flower3; 
     flower2.Location = new Point(panel1.Location.X + 10, panel1.Location.Y + 10); 
     flower2.Size = new System.Drawing.Size(pictureBox2.Size.Width, pictureBox2.Size.Height); 
     flower2.Parent = panel1; 
     this.Controls.Add(flower2); 

     flower2.BringToFront(); 
     flower2.MouseMove += new MouseEventHandler(flower2_MouseMove); 
     flower2.MouseDown += new MouseEventHandler(flower2_MouseDown); 
    } 

    private void flower2_MouseDown(object sender, MouseEventArgs e) 
    { 
     if (e.Button == System.Windows.Forms.MouseButtons.Left) 
     { 
      MouseDownLocation = e.Location; 
     } 
    } 

    private void flower2_MouseMove(object sender, MouseEventArgs e) 
    { 
     if (e.Button == System.Windows.Forms.MouseButtons.Left) 
     { 
      flower2.Left = e.X + flower2.Left - MouseDownLocation.X; 
      flower2.Top = e.Y + flower2.Top - MouseDownLocation.Y; 
     } 
    } 

我希望它做的是被點擊圖像時,創建一個新的,並能夠將它拖放。只有當我將代碼放在頁面頂部時,我才能成功。這不是我想要的,因爲我希望能夠添加儘可能多的圖像。我嘗試了很多不同的方法。錯誤在:

 flower2.Left = e.X + flower2.Left - MouseDownLocation.X; 
     flower2.Top = e.Y + flower2.Top - MouseDownLocation.Y; 

在flower2名下的所有單詞。這是因爲,我已經在pictureBox2_Click中定義了flower2,所以每次點擊一個新的PictureBox都會生成。但是,我需要做到這一點,以便可以根據需要生成儘可能多的圖像,而不必將其放在頁面的頂部,這樣就可以一次只使用一個圖像。

回答

0

您製作的每個圖片框都被路由到這些事件,因此sender對象是圖片框,您只需將它轉換爲正確的類型然後移動即可。

PictureBox pb = (PictureBox)sender; 
pb.Left = e.X + pb.Left - MouseDownLocation.X; 
+0

哦哇!非常感謝!它甚至在我的pictureBoxes背景中修復了我的透明度問題!非常感謝! – user2730088