2014-06-29 53 views
0

所以,我有一個背景圖像(picturebox)和一些拼圖拼圖(pictureboxes動態創建名爲pic [i])隨機位置的形式。如何拖動動態創建的圖片框?

我有這段代碼在for循環中創建件。

pic[i].MouseDown += new MouseEventHandler(picMouseDown); 
    pic[i].MouseMove += new MouseEventHandler(picMouseMove); 
    pic[i].MouseUp += new MouseEventHandler(picMouseUp); 

下面我顯示相應的事件。

int x = 0; 
    int y = 0; 
    bool drag = false; 

    private void picMouseDown(object sender, MouseEventArgs e) 
    { 
     // Get original position of cursor on mousedown 
     x = e.X; 
     y = e.Y; 
     drag = true; 
    } 

    private void picMouseMove(object sender, MouseEventArgs e) 
    { 
     if (drag) 
     { 
      // Get new position of picture 
      pic[i].Top += e.Y - y; //this i here is wrong 
      pic[i].Left += e.X - x; 
      pic[i].BringToFront(); 
     } 
    } 

    private void picMouseUp(object sender, MouseEventArgs e) 
    { 
     drag = false; 
    } 

所以,我知道里面的「picMouseMove」,「I」具有當for循環結束了它的價值。

我想要做的就是在「picMouseMove」事件上獲取pic [i] id,以便用戶實際上可以成功拖動拼圖。

回答

0

您需要將轉換成sender轉換爲PictureBox。然後你可以像訪問它的名字那樣訪問它。

簡單地改變

private void picMouseMove(object sender, MouseEventArgs e) 
{ 
    if (drag) 
    { 
     // Get new position of picture 
     pic[i].Top += e.Y - y; //this i here is wrong 
     pic[i].Left += e.X - x; 
     pic[i].BringToFront(); 
    } 
} 

private void picMouseMove(object sender, MouseEventArgs e) 
{ 
    if (drag) 
    { 
     PictureBox pb = (PictureBox) sender; 
     // Get new position of picture 
     pb.Top += e.Y - y;  
     pb.Left += e.X - x; 
     pb.BringToFront(); 
    } 
} 
+0

非常好,謝謝你,雖然 「pb.Y」 是錯誤的。 「PictureBox pb =(PictureBox)發件人;」解決它:) – AchiPapakon