Timer to close the application

前端 未结 7 1897
离开以前
离开以前 2021-01-12 02:40

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.         


        
7条回答
  •  长情又很酷
    2021-01-12 03:04

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

提交回复
热议问题