c# - 在运行时使图片框在屏幕上移动
问题描述
我正在使用 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;
}
解决方案
您可以使用“计时器”定期更改 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;
}
}
结果,
推荐阅读
- azure-service-fabric - 如何重新启动 Service Fabric 规模集计算机
- java - Spring @RestController - 服务请求后
- jenkins - 如何传递参数
- android - 如何根据时区设置日历
- webpack - 无法使用 Webpack 4 和 Babel 7 导出默认值
- node.js - Arrow function use that is assigned by a module.export object cannot correctly resolve this
- javascript - 如何在自动表格中定义宽度和高度
- javascript - 如何将数据从 UDP 服务器发送到浏览器?
- javascript - 使用jquery在循环中分页上一个和下一个
- git - 如何显示整个 gitkraken 分支树?