首页 > 解决方案 > 在运行时使图片框在屏幕上移动

问题描述

我正在使用 Windows 窗体(.NET 框架)并试图让图片框在屏幕上移动。我试过使用定时器和这个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-studiowinformspicturebox

解决方案


您可以使用“计时器”定期更改 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;
    }
}

结果,

在此处输入图像描述


推荐阅读