Search code examples
c#windowstimer

Why does the timer stop working after showing a new form?


I am working on a C# project. In MainForm.cs I use a Timer. After 60 seconds the timer control information and a new form will be displayed.

 private void timer1_Tick(object sender, EventArgs e)
 {
    timer1.Enabled = true;
    timer1.Interval = 60000;

    ///new message if exist
    
   ...Check Database Statement
        frm_newmessage frm_message = new frm_newmessage();
        frm_show.ShowDialog();
    }
  
}

After showing the new message form and back to mainForm, the timer has stopped working.

private void MainForm_Load(object sender, EventArgs e)
{
    timer1_Tick(sender, e);
}

How can I start the timer again after closing the new message Form and back to MainForm?


Solution

  • You need to start your timer in the main form load. The Tick event handler will be called once every X milliseconds (where X is whatever you set the Interval property to on the timer). When the Tick event occurs you need to stop your timer and finally start the timer again once the dialog window you display has been closed.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
    
                timer1.Interval = 2000;
                timer1.Enabled = true;
                timer1.Start();
            }
    
            private void timer1_Tick(object sender, EventArgs e)
            {
                timer1.Stop();
                frm_newmessage frm_message = new frm_newmessage();
                frm_message.ShowDialog();
                timer1.Start();
            }
        }
    }