pra*_*tom 1 .net c# timeout timer winforms
如何在超时时更改按钮文本?我尝试使用以下代码,但它无法正常工作.
private void button1_Click(object sender, EventArgs e)
{
Stopwatch sw = new Stopwatch();
sw.Start();
if (button1.Text == "Start")
{
//do something
button1.Text = "stop"
if (sw.ElapsedMilliseconds > 5000)
{
button1.Text = "Start";
}
}
Run Code Online (Sandbox Code Playgroud)
我该如何更正我的代码?
您需要使用Timer:
Timer t = new Timer(5000); // Set up the timer to trigger on 5 seconds
t.SynchronizingObject = this; // Set the timer event to run on the same thread as the current class, i.e. the UI
t.AutoReset = false; // Only execute the event once
t.Elapsed += new ElapsedEventHandler(t_Elapsed); // Add an event handler to the timer
t.Enabled = true; // Starts the timer
// Once 5 seconds has elapsed, your method will be called
void t_Elapsed(object sender, ElapsedEventArgs e)
{
// The Timer class automatically runs this on the UI thread
button1.Text = "Start";
}
Run Code Online (Sandbox Code Playgroud)
秒表仅用于测量自调用Start()以来经过的时间.
| 归档时间: |
|
| 查看次数: |
1267 次 |
| 最近记录: |