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

The*_*ask 8 .net c# windows windows-xp clock

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

Cod*_*ray 12

您需要从Windows API P/Invoke SetLocalTime函数.在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;
}
Run Code Online (Sandbox Code Playgroud)

要设置时间,只需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());
}
Run Code Online (Sandbox Code Playgroud)

但请注意,调用进程必须具有相应的权限才能调用此函数.在Windows Vista及更高版本中,这意味着您必须请求进程提升.


或者,您可以使用该SetSystemTime功能,该功能允许您以UTC(协调世界时)设置时间.使用相同的SYSTEMTIME结构,并且以相同的方式调用这两个函数.


Teo*_*gul 6

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

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);
Run Code Online (Sandbox Code Playgroud)