使图片框在运行时在屏幕上移动

问题描述 投票:0回答:1

我正在使用Windows窗体(.NET Framework),并试图使图片框在屏幕上移动。我曾尝试使用计时器,而此while循环却在while循环的情况下没有出现图像(应该是平面),并且使用计时器使删除过去的图片框变得很困难,因此它们看上去会生成序列飞机。我该如何完成?它与Sleep()有关吗?

 private void Button1_Click(object sender, EventArgs e)
    {
        //airplane land
        //drawPlane(ref locx, ref locy);
        //timer1.Enabled = true;
        while (locx > 300)
        {
            var picture = new PictureBox
            {
                Name = "pictureBox",
                Size = new Size(30, 30),
                Location = new System.Drawing.Point(locx, locy),
                Image = Properties.Resources.plane2, //does not appear for some reason

            };

            this.Controls.Add(picture);

            Thread.Sleep(500);

            this.Controls.Remove(picture);
            picture.Dispose();
            locx = locx - 50;


        }
c# visual-studio winforms picturebox
1个回答
0
投票

您可以使用“计时器”定期更改PictureBox的位置。这是一个简单的演示,您可以使用Timer Class进行引用。

public partial class Form1 : Form
{

    private System.Timers.Timer myTimer;
    public Form1()
    {
        InitializeComponent();

        myTimer = new System.Timers.Timer(100);
        myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed);
        myTimer.AutoReset = true;
        myTimer.SynchronizingObject = this;
    }
    private void myTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        pictureBox1.Location = new Point(pictureBox1.Location.X + 1, pictureBox1.Location.Y);
    }

    private void btStart_Click(object sender, EventArgs e)
    {
        myTimer.Enabled = true;
    }
}

结果,

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.