Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer to close the application

Tags:

c#

timer

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?

like image 821
prvit Avatar asked Nov 29 '12 13:11

prvit


1 Answers

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 :)

like image 71
Picrofo Software Avatar answered Oct 14 '22 05:10

Picrofo Software