Timer to close the application

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

    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:

        public Form1() {
            InitializeComponent();
            DateTime now = DateTime.Now;  // avoid race
            DateTime when = new DateTime(now.Year, now.Month, now.Day, 23, 0, 0);
            if (now > when) when = when.AddDays(1);
            timer1.Interval = (int)((when - now).TotalMilliseconds);
            timer1.Start();
        }
        private void timer1_Tick(object sender, EventArgs e) {
            this.Close();
        }
    

提交回复
热议问题