定时器使用标签

时间:2013-11-08 21:07:16

标签: c# timer label

所以,这似乎是一个常见的问题,但我似乎无法找到一种方法来做到这一点。我有一个C#Form应用程序,它发送给imap客户端并处理电子邮件。我希望在表单上显示一个格式为“08:45”(持续8分45秒)的计时器,让用户知道自单击按钮开始此过程以来已经过了多长时间。

我希望计时器在我的进程明显结束后停止。

private void btn_ImportEmail_Click(object sender, EventArgs e)
{
    this.timer = new System.Timers.Timer();
    this.lblTimer = new System.Windows.Forms.Label();
    ((System.ComponentModel.ISupportInitialize) (this.timer)).BeginInit();
    this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimerElapsed);

    //connect to email and download messages...

    this.timer.Enabled = true;
    this.timer.SynchronizingObject = this;
    timer.Interval = 1000;
    timer.Start();
    for (int I = 0 ; I <= messages.count() - 1; I++)
    {
        //process emails
    }
    timer.EndInit();
}

private void timer1_Tick(object sender, EventArgs e)
{
    lblTimer.Text = DateTime.Now.ToString("mm:ss");
}

private void OnTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    lblTimer.Text = DateTime.Now.ToString("mm:ss");
   // lblTimer.Text = string.Format("{0:mm:ss}", DateTime.Now);
}

2 个答案:

答案 0 :(得分:0)

以下SO Q / A可能会回答您的问题...

Display the running time of part of a program in a label

我建议您根据需要更改格式。

答案 1 :(得分:0)

我看到的第一件事是你正在使用DateTime.Now,它将为你提供当前的分钟和秒,而不是经过的分钟和秒。第二件事,也就是主要的事情是,由于你在主UI的线程中处理你的电子邮件,你要防止你的标签被更新,你最好不要再考虑使用后台工作者了。

根据Idle_Mind的评论编辑添加DateTime对象而不是计数器

public partial class Form1 : Form
{
    BackgroundWorker bgw = new BackgroundWorker();
    Timer timer = new Timer();
    DateTime startTime;
    public Form1()
    {
        InitializeComponent();
        timer.Interval = 1000;
        timer.Tick += timer_Tick;
        bgw.DoWork += bgw_DoWork;
        bgw.RunWorkerCompleted+=bgw_RunWorkerCompleted;

    }

    void timer_Tick(object sender, EventArgs e)
    {

        label1.Text =((TimeSpan)DateTime.Now.Subtract(startTime)).ToString("mm\\:ss");

    }

    void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        timer.Stop();
    }

    void bgw_DoWork(object sender, DoWorkEventArgs e)
    {
        for (int I = 0 ; I <= messages.count() - 1; I++)
        {
            //process emails
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        bgw.RunWorkerAsync();
        startTime = DateTime.Now;
        timer.Start();
    }
}