我知道这是一个常见问题,但我似乎无法正确解决。我有一个表单,可以使用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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句