通过计时器和 C# 中的循环制作多个 PictureBoxes

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

我的一个朋友让我写一个程序,在屏幕上生成小鸡的照片。因此,我编写了一个全屏程序,然后尝试生成大量带有鸡图片的图片框。全屏有效,但图片框没有出现。有帮助吗?

        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);
        }

    }

计时器已启用,MessageBox 正常工作。

如果我的计算正确,你的 windows 将在 20 分钟后出现。放弃睡眠或考虑在每个计时器滴答声中创建一个新的 window。

它们没有出现的原因是你在睡觉时阻塞了 Windows 消息泵

虽然最好避免使用带有 void returns 的异步方法,但考虑到它是一个必须为 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());
    }

}