Timer to close the application

前端 未结 7 1810
离开以前
离开以前 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:16

    I'm assuming you're talking about Windows Forms here. Then this might work (EDIT Changed the code so this.Invoke is used, as we're talking about a multi-threaded timer here):

    void  myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
    {
        if (DateTime.Now.Hour >= 23)
            this.Invoke((Action)delegate() { Close(); });
    }
    

    If you switch to using the Windows Forms Timer, then this code will work as expected:

    void  myTimer_Elapsed(object sender, EventArgs e) 
    {
        if (DateTime.Now.Hour >= 23)
            Close();
    }
    

提交回复
热议问题