Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer updating label

I know this is a common question but I can't seem to get it right. I have a form that goes out to gmail and processes some emails. I want to have a timer on the form to count how long the action has been running for. So once a user click the "start import" button I want the timer to start and once the "finished" messagebox appears it should stop. Here is what I have so far

Right now, the timer is just stays at the default text of "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;
        }
}
}
}
like image 223
MaylorTaylor Avatar asked Feb 14 '23 16:02

MaylorTaylor


1 Answers

This is just one of many ways to do it. Of course, I would do it on background worker but this is legit way to get what you want:

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();
}   
like image 154
T.S. Avatar answered Feb 27 '23 12:02

T.S.