我想创建一个让我的应用程序等待X秒的方法,然后继续执行一行脚本。例如,在阅读了许多类似的帮助主题之后,这是我到目前为止的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
methods.WriteTextToScreen(label1, "Hello!");
methods.sleepFor(1);
methods.WriteTextToScreen(label1, "Welcome!");
methods.sleepFor(1);
methods.WriteTextToScreen(label1, "Allo!");
}
public class methods
{
public static int timeSlept;
public static void WriteTextToScreen(Label LabelName, string text)
{
LabelName.Text = text;
}
public static void sleepFor(int seconds)
{
timeSlept = 0;
System.Timers.Timer newTimer = new System.Timers.Timer();
newTimer.Interval = 1000;
newTimer.AutoReset = true;
newTimer.Elapsed += new System.Timers.ElapsedEventHandler(newTimer_Elapsed);
newTimer.Start();
while (timeSlept < seconds)
{
Application.DoEvents();
}
Application.DoEvents();
}
public static void newTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
timeSlept = IncreaseTimerValues(ref timeSlept);
Application.DoEvents();
}
public static int IncreaseTimerValues(ref int x)
{
int returnThis = x + 1;
return returnThis;
}
}
}
}
我想要做的是让我的程序执行methods.WriteTextToScreen(label1,“Hello!”) 然后等待1秒钟,然后以同样的方式继续。问题是表单I显示文本根本没有出现,直到它写了“Allo!”。在屏幕上,所以它第一次出现就已经说明了。我做错了什么,或者没有办法做到这一点?
答案 0 :(得分:0)
表单在构造之前不显示,即Form1中的所有代码都已运行。有关表单构造函数的信息,请参阅此处:http://msdn.microsoft.com/en-us/library/system.windows.forms.form.form.aspx
要解决您的问题,您可以将writeTextToScreen和sleep代码移动到加载方法的表单中。见http://msdn.microsoft.com/en-us/library/system.windows.forms.form.onload.aspx