2015-10-26 38 views
0

我創建了5個PictureBox「形狀」,我​​希望它們在程序啓動時自動移動到左側。所以在timer1_Tick方法中,我使用了「Shapes [i] .Left - = 2」,據說「Shapes」不在實際的上下文中,所以我怎樣才能使「ShapePipes」方法?C#如何使PictureBox自動移動?

public partial class Form1 : Form 
{ 

    int i = 0; 
    int N = 5; 
    int yspeed; 
    int gravity = 2; 

    public Form1() 
    { 
     InitializeComponent(); 
     this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown); 

    } 

    private void Form1_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (e.KeyCode == Keys.Space) 
     { 
      yspeed = -15; 
     } 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 

     CreatePipes(1); 
    } 

    public void CreatePipes(object Number) 
    { 

     PictureBox[] Shapes = new PictureBox[N]; 
     for (i = 0; i < N; i++) 
     { 
      Shapes[i] = new PictureBox(); 
      Shapes[i].Name = "ItemNum_" + i.ToString(); 
      Shapes[i].Location = new Point(300 + 120 * i, 250); 
      Shapes[i].Size = new Size(30, 1000); 
      Shapes[i].BackColor = Color.Green; 

      Shapes[i].Visible = true; 
      this.Controls.Add(Shapes[i]); 
     } 
    } 

    private void bird_Click(object sender, EventArgs e) 
    { 

    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     for (i = 0; i < N; i++) 
     { 
      Shapes[i].Left -= 2; //So the problem is here. Shapes[i] isn't in the actual context. But I don't know to to make it global from CreatePipes 
     } 


     yspeed += gravity; 
     bird.Top += yspeed; 


    } 



} 

}

+0

嘗試調用UpdateLayout請或UI元素的更新方法來刷新他們 –

回答

1

您必須聲明PictureBox[] Shapes以上CreatePipes功能,在Form1類。然後在CreatePipes FUNC,改變PictureBox[] Shapes = new PictureBox[N];Shapes = new PictureBox[N];

+0

謝謝你這麼多,它的工作:d – NewBieBR