Search code examples
c#timerpicturebox

Make multiple PictureBoxes via a timer and a loop in C#


A friend of mine asked me to write a program that spawns photos of chickens all over the screen. So, I wrote a program that fullscreen's itself then attempts to generate tons of pictureboxes with a picture of a chicken in them. The fullscreen works, but the pictureboxes don't appear. Any help?

        private void timer1_Tick(object sender, EventArgs e)
    {

        for (int i = 1; i < 2500; i++)
        {
            Thread.Sleep(500);
            PictureBox pb = new PictureBox();
            this.Controls.Add(pb);
            pb.Visible = true;
            pb.Enabled = true;
            Random r = new Random();
            pb.Image = Properties.Resources.chikoon;
            //pb.SetBounds(xB, yB, 72, 78);
            int xB = r.Next(0, 1920);
            int yB = r.Next(0, 1080);
            MessageBox.Show(xB.ToString() + ", " + yB.ToString());

            pb.Location = new Point(xB, yB);
        }

    }

The timer is enabled and the MessageBox does work.


Solution

  • Although it's best to avoid using async methods with void returns, I don't think there is much of a problem with this one, considering how it's an event handler that must be void;

    private async void timer1_Tick(object sender, EventArgs e) {
        timer1.Stop();
        for (int i = 1; i < 2500; i++) {
            await Task.Delay(500); // Thread.Sleep blocks the program
            PictureBox pb = new PictureBox();
            pb.Image = Properties.Resources.chikoon;
            // add the line below to make the image fit in the PictureBox
            pb.SizeMode = PictureBoxSizeMode.Zoom; //---> resize the image to fit the PictureBox      
            pb.Visible = false; // set it to true only after you've positioned the PictureBox
            this.Controls.Add(pb); // otherwise it will appear at (0, 0) and then move to a new location
            Random r = new Random();
            int xB = r.Next(0, 1920);
            int yB = r.Next(0, 1080);
            pb.Location = new Point(xB, yB);
            pb.Visible = true;
    
            MessageBox.Show(xB.ToString() + ", " + yB.ToString());
        }
    
    }