如何使用 C# 将 Windows 系统时钟设置为正确的本地时间?
最佳答案
您需要 P/Invoke SetLocalTime
function从 Windows API。在 C# 中这样声明:
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool SetLocalTime(ref SYSTEMTIME lpSystemTime);
[StructLayout(LayoutKind.Sequential)]
internal struct SYSTEMTIME
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek; // ignored for the SetLocalTime function
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds;
}
要设置时间,您只需使用适当的值初始化SYSTEMTIME
结构的一个实例,然后调用该函数。示例代码:
SYSTEMTIME time = new SYSTEMTIME();
time.wDay = 1;
time.wMonth = 5;
time.wYear = 2011;
time.wHour = 12;
time.wMinute = 15;
if (!SetLocalTime(ref time))
{
// The native function call failed, so throw an exception
throw new Win32Exception(Marshal.GetLastWin32Error());
}
但是,请注意,调用进程必须具有适当的权限才能调用此函数。在 Windows Vista 及更高版本中,这意味着您将必须请求进程提升。
或者,您可以使用 SetSystemTime
function ,它允许您以 UTC(协调世界时)设置时间。使用相同的 SYSTEMTIME
结构,并且以相同的方式调用这两个函数。
关于c# - 如何使用 C# 将 Windows 系统时钟设置为正确的本地时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6083200/