定时器更新标签

时间:2013-11-13 17:29:29

标签: c# winforms timer label

我知道这是一个常见的问题,但我似乎无法做到正确。我有一个表格可以发送到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;
        }
}
}
}

1 个答案:

答案 0 :(得分:5)

这只是众多方法之一。当然,我会在后台工作者那里做,但这是获得你想要的合法方式:

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();
}