4

我知道这是一个常见问题,但我似乎无法正确回答。我有一个发送到 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;
        }
}
}
}
4

1 回答 1

8

这只是众多方法中的一种。当然,我会在后台工作人员上执行此操作,但这是获得您想要的东西的合法方式:

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();
}   
于 2013-11-13T19:48:28.467 回答