gpt4 book ai didi

c# - 在 C# 中使用超时更改按钮的文本

转载 作者:太空宇宙 更新时间:2023-11-03 20:11:39 26 4
gpt4 key购买 nike

如何更改超时按钮的文本?我尝试了以下代码,但它不起作用。

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";

}
}

如何更正我的代码?

最佳答案

您需要使用 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";
}

秒表仅用于测量自调用 Start() 以来经过了多少时间。

关于c# - 在 C# 中使用超时更改按钮的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19681715/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com