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?
The first problem you have to fix is that a System.Timers.Timer won’t work. It runs the Elapsed event handler on a thread-pool thread, such a thread cannot call the Close method of a Form or Window. The simple workaround is to use a synchronous timer, either a System.Windows.Forms.Timer or a DispatcherTimer, it isn’t clear from the question which one applies.
The only other thing you have to do is to calculate the Interval property value for the timer. That’s fairly straight-forward DateTime arithmetic. If you always want the window to close at, say, 11 o’clock in the evening then write code like this: