问题
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#.
Note: I tried out the SystemEvent.TimeChanged event, but it works only if the user manually changes the time / date from the control panel.
回答1:
Can you simply work out the number of seconds until midnight, and then sleep for that long?
回答2:
@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.
回答3:
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;
}
回答4:
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.
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)); } }
回答5:
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.
来源:https://stackoverflow.com/questions/295235/getting-notified-when-the-datetime-changes-in-c-sharp