gpt4 book ai didi

c# - 关闭应用程序的计时器

转载 作者:太空狗 更新时间:2023-10-29 17:31:39 25 4
gpt4 key购买 nike

如何在 C# 中制作一个强制应用程序在指定时间关闭的计时器?我有这样的东西:

void  myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (++counter == 120)
this.Close();
}

但在这种情况下,应用程序将在计时器运行 120 秒后关闭。我需要一个计时器,例如在 23:00:00 关闭应用程序。有什么建议吗?

最佳答案

您必须解决的第一个问题是 System.Timers.Timer 无法工作。它在线程池线程上运行 Elapsed 事件处理程序,这样的线程不能调用 Form 或 Window 的 Close 方法。简单的解决方法是使用同步计时器,无论是 System.Windows.Forms.Timer 还是 DispatcherTimer,从问题中不清楚哪一个适用。

您唯一需要做的另一件事是计算计时器的 Interval 属性值。这是相当简单的 DateTime 算术。如果你总是希望窗口在晚上 11 点关闭,那么编写如下代码:

    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();
}

关于c# - 关闭应用程序的计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13626454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com