gpt4 book ai didi

c# - 定时器更新标签

转载 作者:行者123 更新时间:2023-12-04 23:49:03 25 4
gpt4 key购买 nike

我知道这是一个常见问题,但我似乎无法正确回答。我有一个表格可以发送到 gmail 并处理一些电子邮件。我想在表单上有一个计时器来计算操作运行了多长时间。因此,一旦用户单击“开始导入”按钮,我希望计时器启动,一旦出现“完成”消息框,它就会停止。这是我到目前为止所拥有的

现在,计时器只是停留在默认文本“00”;

namespace Import
{
public partial class Form1 : Form
{
Timer timer;
public Form1()
{
InitializeComponent();

}

private void btn_Import_Click(object sender, EventArgs e)
{
timer = new Timer();
timer.Interval = (1000);
timer.Enabled = true;
timer.Start();
timer.Tick += new EventHandler(timer_Tick);

// code to import emails

MessageBox.Show("The import was finished");
private void timer_Tick(object sender, EventArgs e)
{

if (sender == timer)
{
lblTimer.Text = GetTime();
}
}
public string GetTime()
{
string TimeInString = "";
int min = DateTime.Now.Minute;
int sec = DateTime.Now.Second;

TimeInString = ":" + ((min < 10) ? "0" + min.ToString() : min.ToString());
TimeInString += ":" + ((sec < 10) ? "0" + sec.ToString() : sec.ToString());
return TimeInString;
}
}
}
}

最佳答案

这只是实现它的众多方法之一。当然,我会在后台工作人员上执行此操作,但这是获得所需内容的合法方式:

Timer timer;
Stopwatch sw;

public Form1()
{
InitializeComponent();

}

private void btn_Import_Click(object sender, EventArgs e)
{
timer = new Timer();
timer.Interval = (1000);
timer.Tick += new EventHandler(timer_Tick);
sw = new Stopwatch();
timer.Start();
sw.Start();

// start processing emails

// when finished
timer.Stop();
sw.Stop();
lblTime.text = "Completed in " + sw.Elapsed.Seconds.ToString() + "seconds";
}


private void timer_Tick(object sender, EventArgs e)
{
lblTime.text = "Running for " + sw.Elapsed.Seconds.ToString() + "seconds";
Application.DoEvents();
}

关于c# - 定时器更新标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19960438/

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