如何在Microsoft Visual C#5秒后显示图片?

我希望这个图像计时器在5秒后出现,但不知道该怎么做。 到目前为止,我已经使图像在表单周围反弹但我希望图像在5秒后反弹时出现。

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Bounce { public partial class Form1 : Form { int horiz, vert, step; public Form1() { InitializeComponent(); } private void timer1_Tick_1(object sender, EventArgs e) { //image is moved at each interval of the timer goblin.Left = goblin.Left + (horiz * step); goblin.Top = goblin.Top + (vert * step); // if goblin has hit the RHS edge, if so change direction left if ((goblin.Left + goblin.Width) >= (Form1.ActiveForm.Width - step)) horiz = -1; // if goblin has hit the LHS edge, if so change direction right if (goblin.Left = (Form1.ActiveForm.Height - step)) vert = -1; // if goblin has hit the top edge, if so change direction downwards if (goblin.Top < step) vert = 1; } private void Form1_Load_1(object sender, EventArgs e) { //Soon as the forms loads activate the goblin to start moving //set the intial direction horiz = 1; //start going right vert = 1; //start going down step = 5; timer1.Enabled = true; } } } 

这应该做到这一点。

 using System.Timers; // this is Where the timer class lives. Timer fiveSecondTimer = new Timer(5000); fiveSecondTimer.Elapsed += () => { ShowImageHere }; //This is short hand fiveSecondTimer.Start(); 

创建一个名为startTime的私有变量。 启动计时器时,将其值设置为DateTime.Now 。 每次计时器滴答时,您可以检查当前DateTime.Now与存储的startTime之间的差异,看看它是否超过5秒。

 int horiz, vert, step; DateTime startTime; public Form1() { InitializeComponent(); } private void timer1_Tick_1(object sender, EventArgs e) { var timeElapsed = (DateTime.Now - startTime).TotalSeconds; // Show image if this is greater than 300 //image is moved at each interval of the timer goblin.Left = goblin.Left + (horiz * step); goblin.Top = goblin.Top + (vert * step); // if goblin has hit the RHS edge, if so change direction left if ((goblin.Left + goblin.Width) >= (Form1.ActiveForm.Width - step)) horiz = -1; // if goblin has hit the LHS edge, if so change direction right if (goblin.Left <= step) horiz = 1; // if goblin has hit the bottom edge, if so change direction upwards if ((goblin.Top + goblin.Height) >= (Form1.ActiveForm.Height - step)) vert = -1; // if goblin has hit the top edge, if so change direction downwards if (goblin.Top < step) vert = 1; } private void Form1_Load_1(object sender, EventArgs e) { //Soon as the forms loads activate the goblin to start moving //set the intial direction horiz = 1; //start going right vert = 1; //start going down step = 5; timer1.Enabled = true; timer1.Start(); startTime = DateTime.Now; } 

我的第一直觉就是说要使用Thread.Sleep(),但我想知道这对你是否有效,因为你似乎不想阻止整个执行5秒钟。

我看到你已经在使用Timer对象来控制这个妖精家伙的游戏循环。 有没有任何理由你不能只有另一个具有5秒间隔的计时器,并且一旦它打勾,在它上面调用停止以防止任何未来的计时事件,并在他的旅程中启动地精?