Here's a class I use to handle this. It's similar to @sll's answer, however takes into account the system time changing and also will trigger each midnight instead of only once.
static class MidnightNotifier
{
private static readonly Timer timer;
static MidnightNotifier()
{
timer = new Timer(GetSleepTime());
timer.Elapsed += (s, e) =>
{
OnDayChanged();
timer.Interval = GetSleepTime();
};
timer.Start();
SystemEvents.TimeChanged += OnSystemTimeChanged;
}
private static double GetSleepTime()
{
var midnightTonight = DateTime.Today.AddDays(1);
var differenceInMilliseconds = (midnightTonight - DateTime.Now).TotalMilliseconds;
return differenceInMilliseconds;
}
private static void OnDayChanged()
{
var handler = DayChanged;
if (handler != null)
handler(null, null);
}
private static void OnSystemTimeChanged(object sender, EventArgs e)
{
timer.Interval = GetSleepTime();
}
public static event EventHandler<EventArgs> DayChanged;
}
Since it's a static class, you can subscribe to the event using code like:
MidnightNotifier.DayChanged += (s, e) => { Console.WriteLine("It's midnight!"); };