从应用程序设置系统日期和时间
答
如果你的设备上有NTP客户端,你可以使用它。服务器在多串字符串注册表值中配置为:
[HKLM\Services\TIMESVC]
server
以下是代码如何强制客户端进行同步。否则,有客户端同步的频率(MS的DWORD)注册表值:
[HKLM\Services\TIMESVC]
Refresh
强制同步:
internal static class NativeMethods
{
internal const int INVALID_HANDLE_VALUE = -1;
internal const int IOCTL_SERVICE_CONTROL = (0x104 << 16) | (7 << 2);
internal const uint GENERIC_READ = 0x80000000;
internal const uint GENERIC_WRITE = 0x40000000;
internal const int OPEN_EXISTING = 3;
[DllImport("coredll.dll", SetLastError = true)]
internal static extern IntPtr CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
[DllImport("coredll.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeviceIoControl(
IntPtr hDevice,
int dwIoControlCode,
byte[] lpInBuffer,
int nInBufferSize,
byte[] lpOutBuffer,
int nOutBufferSize,
ref int lpBytesReturned,
IntPtr lpOverlapped);
[DllImport("coredll.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CloseHandle(IntPtr hObject);
}
internal static class TimeServer
{
public static bool SyncTime()
{
byte[] input = System.Text.Encoding.Unicode.GetBytes("Sync\0");
return TimeServer.DeviceIOCTL("NTP0:", NativeMethods.IOCTL_SERVICE_CONTROL, input);
}
private static bool DeviceIOCTL(string deviceName, int ioctl, byte[] input)
{
int size = 0;
return TimeServer.DeviceIOCTL(deviceName, ioctl, input, null, ref size);
}
public static bool DeviceIOCTL(string deviceName, int ioctl, byte[] input, byte[] output, ref int bytesReceived)
{
bool result = false;
IntPtr deviceHandle = NativeMethods.CreateFile(
deviceName,
NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE,
0,
IntPtr.Zero,
(uint)NativeMethods.OPEN_EXISTING,
0,
IntPtr.Zero);
if (deviceHandle.ToInt32() != NativeMethods.INVALID_HANDLE_VALUE)
{
try
{
result = NativeMethods.DeviceIoControl(
deviceHandle,
ioctl,
input,
(input == null) ? 0 : input.Length,
output,
(output == null) ? 0 : output.Length,
ref bytesReceived,
IntPtr.Zero);
}
finally
{
NativeMethods.CloseHandle(deviceHandle);
}
}
return result;
}
}
答
我能够使用SNTP Client Project from the Codeproject
进行同步的时间。然而,不得不改变Pinvoke声明使用[DllImport("coredll.dll")]
而不是[DllImport("kernal32.dll")]
我做了这个跑步风移动6.1,紧凑框架3.5
+0
此新版本:http://bocan.ro/Media/Default/Downloads/InternetTime.zip – franDayz 2016-04-11 14:14:07
可能重复http://stackoverflow.com/questions/738615/set-device-time-on-net-cf – 2010-05-04 06:14:46
@Sundar:很多没有一度接受答案的问题。开始标记答案或不要惊讶,人们不回答你。 – Shaihi 2010-05-04 06:33:55