C#如何让PictureBoxs自动移动?

时间:2015-10-26 19:56:05

标签: c# picturebox

我创建了5个PictureBox“Shapes”,我希望它们在程序启动时自动向左移动。所以在timer1_Tick方法中,我使用“Shapes [i] .Left - = 2”,它说“形状”不在实际上下文中,所以如何从“CreatePipes”中创建Shapes [i]全局方法

    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;   


    }



}

}

1 个答案:

答案 0 :(得分:1)

您必须在Form1类中的CreatePipes函数之上声明PictureBox[] Shapes。然后在CreatePipes func中,将PictureBox[] Shapes = new PictureBox[N];更改为Shapes = new PictureBox[N];