我使用以下程序更改了系统日期时间。
public struct SystemTime
{
public ushort Year;
public ushort Month;
public ushort DayOfWeek;
public ushort Day;
public ushort Hour;
public ushort Minute;
public ushort Second;
public ushort Millisecond;
};
[DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
public extern static void Win32GetSystemTime(ref SystemTime sysTime);
[DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
public extern static bool Win32SetSystemTime(ref SystemTime sysTime);
private void button1_Click(object sender, EventArgs e)
{`enter code here`
// Set system date and time
SystemTime updatedTime = new SystemTime();
updatedTime.Year = (ushort)2009;
updatedTime.Month = (ushort)3;
updatedTime.Day = (ushort)16;
updatedTime.Hour = (ushort)10;
updatedTime.Minute = (ushort)0;
updatedTime.Second = (ushort)0;
// Call the unmanaged function that sets the new date and time instantly
Win32SetSystemTime(ref updatedTime);
}
系统日期已更改,但时间未更改。我的任务是获取NTP服务器时间并更改NTP服务器时间的系统日期和时间。我正在获取NTP服务器日期和时间并更改日期,但我无法更改系统的时间
你正确地声明了 SetSystemTime(),但后来你忘记正确使用它。 不能忽略返回值。 修复:
if (!Win32SetSystemTime(ref updatedTime)) {
throw new System.ComponentModel.Win32Exception();
}
现在,您将从异常中发现失败的可能原因。 几种可能性,但我们可以猜测:更改时钟需要管理员权限,而您的程序不太可能拥有它们。 必须请求用户允许执行此操作,方法是嵌入要求 UAC 提升的清单。 这个答案显示了如何做到这一点。
以防万一您认为这是不合理的:请记住,更改时钟对运行程序非常具有破坏性。 在 Windows 中运行的许多基本服务都依赖于准确的时钟。 它也不会持续很长时间,Windows会定期联系时间服务器以重新校准时钟。 您必须禁用它,请在 superuser.com 询问。您会遇到的其他问题,例如文件以错误的时间戳写入,计划任务在应该运行时未运行,Web浏览器抱怨不正确的证书,尽管您没有进行任何更改,但您的项目总是重建,但是您需要处理。 别这样。