How to make a timer which forces the application to close at a specified time in C#? I have something like this:
void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (++counter == 120)
this.Close();
}
But in this case, the application will be closed in 120 sec after the timer has ran. And I need a timer, which will close the application for example at 23:00:00. Any suggestions?
You may want to get the current system time. Then, see if the current time matches the time you would like your application to close at. This can be done using DateTime
which represents an instant in time.
Example
public Form1()
{
InitializeComponent();
Timer timer1 = new Timer(); //Initialize a new Timer of name timer1
timer1.Tick += new EventHandler(timer1_Tick); //Link the Tick event with timer1_Tick
timer1.Start(); //Start the timer
}
private void timer1_Tick(object sender, EventArgs e)
{
if (DateTime.Now.Hour == 23 && DateTime.Now.Minute == 00 && DateTime.Now.Second == 00) //Continue if the current time is 23:00:00
{
Application.Exit(); //Close the whole application
//this.Close(); //Close this form only
}
}
Thanks,
I hope you find this helpful :)
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