Jimi2000

SystemTimeWatcher

Jul 29th, 2019
324
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.50 KB | None | 0 0
  1. using System.Diagnostics;
  2. using System.Threading.Tasks;
  3. using Microsoft.Win32;
  4.  
  5.     public class SystemTimeWatcher : IDisposable
  6.     {
  7.         public delegate void SystemTimeChangedEventHandler(object sender, TimeChangedEventArgs e);
  8.         public event SystemTimeChangedEventHandler SystemTimeChangedNotify;
  9.  
  10.         private bool SystemTimeChangedNotifyActive = false;
  11.         Stopwatch sw = new Stopwatch();
  12.  
  13.         public SystemTimeWatcher() { }
  14.  
  15.         public bool InstallTimeChangedNotification()
  16.         {
  17.             if (SystemTimeChangedNotifyActive) return false;
  18.             SystemTimeChangedNotifyActive = true;
  19.             SystemEvents.TimeChanged += this.OnTimeChanged;
  20.             return true;
  21.         }
  22.  
  23.         private async void OnTimeChanged(object sender, EventArgs e)
  24.         {
  25.             if (sw.IsRunning) return;
  26.             sw.Start();
  27.             var args = new TimeChangedEventArgs();
  28.             OnSystemTimeChangedNotify(args);
  29.             await Task.Delay(200).ConfigureAwait(false);
  30.             sw.Stop();
  31.         }
  32.  
  33.         protected virtual void OnSystemTimeChangedNotify(TimeChangedEventArgs e)
  34.             => SystemTimeChangedNotify?.Invoke("System Time Changed", e);
  35.  
  36.         public class TimeChangedEventArgs : EventArgs
  37.         {
  38.             public DateTime CurrentTime { get; set; } = DateTime.Now;
  39.             public int SomeOtherUsefulValue { get; set; }
  40.         }
  41.  
  42.         public void Dispose() => SystemEvents.TimeChanged -= this.OnTimeChanged;
  43.     }
Add Comment
Please, Sign In to add comment