Windows API to trigger the time synchronization

后端 未结 2 647
小蘑菇
小蘑菇 2021-02-05 17:31

Is there a windows API that would achieve the equivalent of clicking the \"Update now\" button in the \"Date and time properties\"/\"Internet time\" tab (opened by double clicki

2条回答
  •  生来不讨喜
    2021-02-05 17:58

    This seems to work:

    using System;
    using System.Runtime.InteropServices;
    
    namespace ClockResync
    {
        class Program
        {
            [DllImport("w32time.dll")]
            public static extern uint W32TimeSyncNow([MarshalAs(UnmanagedType.LPWStr)]String computername, bool wait, uint flag);
            static void Main(string[] args)
            {
                Console.WriteLine(W32TimeSyncNow("computername", true, 8).ToString());
                Console.ReadLine();
            }
        }
    }
    

    It's undocumented so I'm not exactly sure what the possible flags are, but 8 seems to do the job just fine - tested with my system clock. If you're running Windows 64-bit, compile for 64-bit or you'll be getting access violation exceptions.

    W32TimeQueryStatus should be able to get the last successful sync time. I'll work on that when I have more time.

提交回复
热议问题