C# 如何让图片框自动移动?

C# How to make PictureBoxs move automatically?

我创建了 5 个 PictureBox "Shapes",我希望它们在程序启动时自动向左移动。所以在 timer1_Tick 方法中,我使用 "Shapes[i].Left -= 2",据说 "Shapes" 不在实际上下文中,所以我怎样才能使 [=18] 的 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;   


    }



}

}

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