Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

68 linhas
1.9 KiB

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