2015-10-26 82 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