C#如何让PictureBoxs自动移动?

时间:2021-06-28 20:47:57

I created 5 PictureBox "Shapes" and I want them to move to the left automatically when the program is launched. So in the timer1_Tick method, I use "Shapes[i].Left -= 2", it's said that "Shapes" isn't in the actual context, so How can I make the Shapes[i] global from the "CreatePipes" method?

我创建了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 个解决方案

#1


1  

You have to declare PictureBox[] Shapes above CreatePipes function, in Form1 class. Then in CreatePipes func, change PictureBox[] Shapes = new PictureBox[N]; to Shapes = new PictureBox[N];

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

#1


1  

You have to declare PictureBox[] Shapes above CreatePipes function, in Form1 class. Then in CreatePipes func, change PictureBox[] Shapes = new PictureBox[N]; to Shapes = new PictureBox[N];

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