You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.2 KiB

  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace ThunderboltTimeSync {
  4. class SystemTimeUtils {
  5. public class SystemTimeException : Exception {
  6. public SystemTimeException(int hresult) : base(string.Format("The system time could not be set (HRESULT 0x{0:X8}).", hresult)) {
  7. HResult = hresult;
  8. }
  9. }
  10. private class WindowsAPI {
  11. [StructLayout(LayoutKind.Sequential)]
  12. public struct SYSTEMTIME {
  13. public short wYear;
  14. public short wMonth;
  15. public short wDayOfWeek;
  16. public short wDay;
  17. public short wHour;
  18. public short wMinute;
  19. public short wSecond;
  20. public short wMilliseconds;
  21. };
  22. [DllImport("kernel32.dll")]
  23. public static extern int GetLastError();
  24. [DllImport("kernel32.dll", SetLastError = true)]
  25. public static extern bool SetSystemTime(ref SYSTEMTIME lpSystemTime);
  26. [DllImport("kernel32.dll")]
  27. public static extern void GetSystemTime(ref SYSTEMTIME lpSystemTime);
  28. }
  29. /// <summary>
  30. /// Sets the system time.
  31. /// </summary>
  32. /// <param name="dateTime">The date and time to set the system clock to.</param>
  33. public static void SetSystemTime(DateTime dateTime) {
  34. WindowsAPI.SYSTEMTIME systemTime = new WindowsAPI.SYSTEMTIME();
  35. systemTime.wYear = (short) dateTime.Year;
  36. systemTime.wMonth = (short) dateTime.Month;
  37. // wDayOfWeek is ignored by SetSystemTime
  38. systemTime.wDay = (short) dateTime.Day;
  39. systemTime.wHour = (short) dateTime.Hour;
  40. systemTime.wMinute = (short) dateTime.Minute;
  41. systemTime.wSecond = (short) dateTime.Second;
  42. systemTime.wMilliseconds = (short) dateTime.Millisecond;
  43. bool setSucceeded = WindowsAPI.SetSystemTime(ref systemTime);
  44. if (!setSucceeded) {
  45. throw new SystemTimeException(WindowsAPI.GetLastError());
  46. }
  47. }
  48. /// <summary>
  49. /// Retrieves the current system time.
  50. /// </summary>
  51. /// <returns>The current system time.</returns>
  52. public static DateTime GetSystemTime() {
  53. WindowsAPI.SYSTEMTIME systemTime = new WindowsAPI.SYSTEMTIME();
  54. WindowsAPI.GetSystemTime(ref systemTime);
  55. DateTime systemDateTime = new DateTime(
  56. systemTime.wYear, systemTime.wMonth, systemTime.wDay,
  57. systemTime.wHour, systemTime.wMinute, systemTime.wSecond, systemTime.wMilliseconds
  58. );
  59. return systemDateTime;
  60. }
  61. }
  62. }