问题描述
如何在 C# 中创建一个定时器来强制应用程序在指定时间关闭?我有这样的事情:
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();
}
但在这种情况下,应用程序将在计时器运行后的 120 秒内关闭.我需要一个计时器,它将在例如 23:00:00 关闭应用程序.有什么建议吗?
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?
推荐答案
您必须解决的第一个问题是 System.Timers.Timer 不起作用.它在线程池线程上运行 Elapsed 事件处理程序,这样的线程不能调用 Form 或 Window 的 Close 方法.简单的解决方法是使用同步计时器,System.Windows.Forms.Timer 或 DispatcherTimer,从问题中不清楚哪个适用.
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.
您唯一需要做的另一件事是计算计时器的 Interval 属性值.这是相当简单的 DateTime 算法.如果你总是希望窗口在晚上 11 点关闭,那么编写如下代码:
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();
}
这篇关于关闭应用程序的计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!