如何使用C#将Windows系统时钟设置为正确的本地时间?

lxkprmvk  于 2023-05-19  发布在  Windows
关注(0)|答案(4)|浏览(209)

如何使用C#将Windows系统时钟设置为正确的本地时间?

toiithl6

toiithl61#

您需要从Windows API P/Invoke SetLocalTime function。在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结构,并且以相同的方式调用这两个函数。

zvms9eto

zvms9eto2#

.NET没有为此公开函数,但您可以使用Win32 API SetSystemTime(在kernel32.dll中)方法。要获取UTC时间,您应该使用NTP Protocol Client,然后根据您的区域设置将该时间调整为本地时间。

public struct SYSTEMTIME
{    
  public ushort wYear,wMonth,wDayOfWeek,wDay,wHour,wMinute,wSecond,wMilliseconds;
}

[DllImport("kernel32.dll")]
public extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);

SYSTEMTIME systime = new SYSTEMTIME();
systime = ... // Set the UTC time here
SetSystemTime(ref systime);
j7dteeu8

j7dteeu83#

这里有几篇文章介绍了如何做到这一点,包括查询原子钟以获得正确的时间。
http://www.codeproject.com/KB/IP/ntpclient.aspx
http://www.codeproject.com/KB/datetime/SNTPClient.aspx

sigwle7e

sigwle7e4#

要解决SE_SYSTEMTIME_NAME权限问题,请尝试创建一个计划任务来运行应用程序并启用“以最高权限运行”。

相关问题