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;
        }
}
}
}
                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();
}   
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With