在 c# 中的日期时间更改时收到通知

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/295235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 22:02:14  来源:igfitidea点击:

Getting notified when the datetime changes in c#

c#eventsdatetimesystemevent

提问by

Recently I was trying to make a calendar application that will display the current year-month-date to the user. The problem is, if the user is gonna keep my application running even for the next day, how do I get notified ?? How shall I change the date displayed ? I don't wanna poll the current date to update it. Is this possible in c#.

最近我正在尝试制作一个日历应用程序,它将向用户显示当前的年月日。问题是,如果用户要让我的应用程序在第二天继续运行,我如何得到通知?我该如何更改显示的日期?我不想轮询当前日期来更新它。这在 c# 中可能吗?

Note: I tried out the SystemEvent.TimeChangedevent, but it works only if the user manually changes the time / date from the control panel.

注意:我尝试了SystemEvent.TimeChanged事件,但它只有在用户从控制面板手动更改时间/日期时才有效。

采纳答案by Oddthinking

Can you simply work out the number of seconds until midnight, and then sleep for that long?

你能简单地计算出到午夜的秒数,然后睡那么长时间吗?

回答by Student for Life

Try looking into monitoring WMI events, you should be able to create a Wql event query that monitors the day of week change (i.e. ManagementEventWatcher etc) and then setup an event handler that fires when the event arrives.

尝试查看监视 WMI 事件,您应该能够创建一个 Wql 事件查询来监视星期几的更改(即 ManagementEventWatcher 等),然后设置一个在事件到达时触发的事件处理程序。

using System;
using System.Management;

class Program
{
    public static void Main()
    {
        WqlEventQuery q = new WqlEventQuery();
        q.EventClassName = "__InstanceModificationEvent ";
        q.Condition = @"TargetInstance ISA 'Win32_LocalTime' AND TargetInstance.Hour = 22 AND TargetInstance.Minute = 7 AND TargetInstance.Second = 59";

        Console.WriteLine(q.QueryString);

        using (ManagementEventWatcher w = new ManagementEventWatcher(q))
        {
            w.EventArrived += new EventArrivedEventHandler(TimeEventArrived);
            w.Start();
            Console.ReadLine(); // Block this thread for test purposes only....
            w.Stop();
        }
    }

    static void TimeEventArrived(object sender, EventArrivedEventArgs e)
    {
        Console.WriteLine("This is your wake-up call");
        Console.WriteLine("{0}", new
        DateTime((long)(ulong)e.NewEvent.Properties["TIME_CREATED"].Value));
    }
}

回答by Student for Life

@OddThinking's answer will work (you could set a timer for the interval instead of sleeping). Another way would be to set a timer with a 1 minute interval and simply check if the system date has changed. Since you are only executing some lightweight code once a minute, I doubt the overhead would be noticable.

@OddThinking 的答案会起作用(您可以为间隔设置计时器而不是睡眠)。另一种方法是设置一个间隔为 1 分钟的计时器,并简单地检查系统日期是否已更改。由于您每分钟只执行一次轻量级代码,我怀疑开销是否会很明显。

回答by Patrik Svensson

How about a thread that checks for change in date. The thread can have some events that the controls that need this information can subscribe to.

检查日期变化的线程怎么样。线程可以有一些事件,需要这些信息的控件可以订阅这些事件。

回答by Case

public void Main()
{

    var T = new System.Timers.Timer();

    T.Elapsed += CallBackFunction;

    var D = (DateTime.Today.AddDays(1).Date - DateTime.Now);

    T.Interval = D.TotalMilliseconds;

    T.Start();

}

private void CallBackFunction(object sender, System.Timers.ElapsedEventArgs e)
{

    (sender as System.Timers.Timer).Interval = (DateTime.Today.AddDays(1).Date - DateTime.Now).TotalMilliseconds;

}