Windows API to trigger the time synchronization
Asked Answered
W

2

13

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 clicking the clock in the taskbar)?

Is there a way to monitor when the time synchronization is triggered by windows and when it succeeds or fails?

Wordless answered 5/5, 2010 at 9:47 Comment(1)
There is documentation of the w32Time.dll interface here: learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/…Smitten
H
13

There is no API exposed by the time service, but to trigger a time synchronization you can use the w32tm command line tool.

In C/C++ you can do something like this:

include <process.h>

...

system("w32tm /resync /nowait");

Take a look at w32tm documentation for further options.

Hindward answered 5/5, 2010 at 11:30 Comment(2)
Not exactly what I needed, but better than nothing. Thanks!Housekeeper
if you get The following error occurred: The service has not been started. (0x80070426) execute net start w32timeSouse
I
3

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.

Iodous answered 13/7, 2016 at 0:39 Comment(1)
thats not C++, thats C#Rauscher

© 2022 - 2024 — McMap. All rights reserved.