Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Diagnostics;
- using System.Threading.Tasks;
- using Microsoft.Win32;
- public class SystemTimeWatcher : IDisposable
- {
- public delegate void SystemTimeChangedEventHandler(object sender, TimeChangedEventArgs e);
- public event SystemTimeChangedEventHandler SystemTimeChangedNotify;
- private bool SystemTimeChangedNotifyActive = false;
- Stopwatch sw = new Stopwatch();
- public SystemTimeWatcher() { }
- public bool InstallTimeChangedNotification()
- {
- if (SystemTimeChangedNotifyActive) return false;
- SystemTimeChangedNotifyActive = true;
- SystemEvents.TimeChanged += this.OnTimeChanged;
- return true;
- }
- private async void OnTimeChanged(object sender, EventArgs e)
- {
- if (sw.IsRunning) return;
- sw.Start();
- var args = new TimeChangedEventArgs();
- OnSystemTimeChangedNotify(args);
- await Task.Delay(200).ConfigureAwait(false);
- sw.Stop();
- }
- protected virtual void OnSystemTimeChangedNotify(TimeChangedEventArgs e)
- => SystemTimeChangedNotify?.Invoke("System Time Changed", e);
- public class TimeChangedEventArgs : EventArgs
- {
- public DateTime CurrentTime { get; set; } = DateTime.Now;
- public int SomeOtherUsefulValue { get; set; }
- }
- public void Dispose() => SystemEvents.TimeChanged -= this.OnTimeChanged;
- }
Add Comment
Please, Sign In to add comment