Skip to content

Instantly share code, notes, and snippets.

@tkouba
Created August 1, 2016 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkouba/ab14b1832c87d59838765f5ae2e2fac1 to your computer and use it in GitHub Desktop.
Save tkouba/ab14b1832c87d59838765f5ae2e2fac1 to your computer and use it in GitHub Desktop.
Windows CE time service control
using System;
using System.Runtime.InteropServices;
namespace Arci.WindowsCE
{
/// <summary>
/// NTP service controller
/// </summary>
public static class TimeService
{
// See https://msdn.microsoft.com/en-us/library/ms899593.aspx
private const uint GENERIC_READ = 0x80000000;
private const uint GENERIC_WRITE = 0x40000000;
//private const uint GENERIC_EXECUTE = 0x20000000;
private const int IOCTL_SERVICE_CONTROL = (0x104 << 16) | (7 << 2);
private const uint OPEN_EXISTING = 3;
[DllImport("coredll.dll", EntryPoint = "CreateFile", SetLastError = true)]
private static extern IntPtr CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
int lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
int hTemplateFile);
[DllImport("coredll.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("coredll.dll", EntryPoint = "DeviceIoControl", SetLastError = true)]
private static extern int DeviceIoControl(
IntPtr hDevice,
uint dwIoControlCode,
byte[] lpInBuffer,
int nInBufferSize,
byte[] lpOutBuffer,
int nOutBufferSize,
out int lpBytesReturned,
IntPtr lpOverlapped);
private static readonly IntPtr invalidHandle = new IntPtr(-1);
/// <summary>
/// Synchronize the system time with te external NTP server
/// </summary>
/// <param name="force">forces the system time to be set, regardless of any time differences between system and server</param>
public static void SyncTime(bool force)
{
// https://msdn.microsoft.com/en-us/library/ms881011.aspx
// Sync - Synchronizes the system with the external NTP server,
// and sets the time according to the settings defined in the registry.
// Set - Synchronizes the system with the external NTP server,
// and forces the system time to be set, regardless of any time differences between system and server.
NtpOperation(force ? "Set\0" : "Sync\0");
}
private static void NtpOperation(string operation)
{
IntPtr hFile = CreateFile("NTP0:", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
if (invalidHandle == hFile)
return;
try
{
byte[] data = System.Text.Encoding.Unicode.GetBytes(operation);
int returned;
int result = DeviceIoControl(hFile, IOCTL_SERVICE_CONTROL, data, data.Length, null, 0, out returned, IntPtr.Zero);
}
finally
{
CloseHandle(hFile);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment