【问题标题】:Make picture box move across screen during runtime在运行时使图片框在屏幕上移动
【发布时间】:2019-12-11 09:38:06
【问题描述】:

我正在使用 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;


        }

【问题讨论】:

  • 使用System.Windows.Forms.Timer 移动控件。您只需要一个 PictureBox:重新定义它在 Timer.Tick 事件中的位置。不要使用Resources 工厂设置 Image 属性:将 Image 分配给 Bitmap 对象,然后在需要时将 Bitmap 分配给 Image 属性,并在不再需要时将其丢弃。

标签: c# visual-studio winforms picturebox


【解决方案1】:

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

结果,

【讨论】:

  • @LarsTech 我不认为 Winforms Timer 是一个好的选择。它与 UI 共享线程,这很可能导致阻塞。
  • WinForms 计时器不会阻止任何内容。
  • Winforms 计时器是单线程的。执行耗时操作时,表单将冻结。而其精度只能达到55毫秒。
  • 您发布的代码可以与 WinForm 的计时器一起使用。您正在使用的计时器... is intended for use as a server-based or service component。真的很简单:WinForm 的应用程序应该使用 WinForm 的 Timer,尤其是尝试学习在其中编程的人。
  • 我没有说不能使用Winforms Timer。就个人而言,我不建议使用它。 a WinForm's app should use a WinForm's Timer?抱歉,我不这么认为。
猜你喜欢
  • 2020-04-04
  • 1970-01-01
  • 2014-06-04
  • 2013-07-11
  • 2015-09-05
  • 2014-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多