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

标签 c# .net windows windows-xp clock

如何使用 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/

相关文章:

将操作系统线程限制在一个 CPU 上会很糟糕吗?

c# - 更改外部窗口的最小尺寸

c# - 在 C# 中,我应该使用 string.Empty 或 String.Empty 或 ""来初始化字符串?

c# - 在 C# 中通过钩子(Hook)重定向 keydown?

c# - 使用在 C# 中声明的虚拟异步任务并在 F# 中覆盖它

.net - 使用/clr :safe to enable unit testing? 编译 C++ 项目有什么缺点

c++ - GetQueuedCompletionStatusEx() 不返回 per-OVERLAPPED 错误代码

c# - SQL Server 将表更改通知 Web 服务器

c# - Debug模式下的 Visual Studio 行突出显示

.net - 无法运行 "GenerateResource"任务,因为 MSBuild 无法创建或连接到运行时为 "CLR4"且体系结构为 "x64"的任务主机