如何使用 C# 将 Windows 系统时钟设置为正确的本地时间?
如何使用 C# 将 Windows 系统时钟设置为正确的本地时间?
How do I set the Windows system clock to the correct local time using C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您将需要 P/Invoke
SetLocalTime
函数 来自 Windows API。在 C# 中这样声明:要设置时间,只需使用适当的值初始化 SYSTEMTIME 结构的实例,然后调用该函数即可。示例代码:
但是,请注意,调用进程必须具有适当的权限才能调用此函数。在 Windows Vista 及更高版本中,这意味着您必须请求进程提升。
或者,您可以使用
SetSystemTime
函数 ,它允许您设置 UTC(协调世界时)时间。使用相同的 SYSTEMTIME 结构,并且以相同的方式调用这两个函数。You will need to P/Invoke the
SetLocalTime
function from the Windows API. Declare it like this in C#:To set the time, you simply initialize an instance of the
SYSTEMTIME
structure with the appropriate values, and call the function. Sample code:However, note that the calling process must have the appropriate privileges in order to call this function. In Windows Vista and later, this means you will have to request process elevation.
Alternatively, you could use the
SetSystemTime
function, which allows you to set the time in UTC (Coordinated Universal Time). The sameSYSTEMTIME
structure is used, and the two functions are called in an identical fashion..NET 没有为此公开函数,但您可以使用 Win32 API SetSystemTime(在 kernel32.dll 中)方法。要获取 UTC 时间,您应该使用 NTP Protocol Client,然后根据您的区域设置将该时间调整为当地时间。
.NET does not expose a function for that but you can use Win32 API SetSystemTime (in kernel32.dll) method. To get UTC time you should use an NTP Protocol Client and then adjust that time to the local time according to your regional settings.
这里有几篇关于如何做到这一点的文章,其中包括查询原子钟的正确时间。
http://www.codeproject.com/KB/IP/ntpclient.aspx
http://www.codeproject.com/KB/datetime/SNTPClient.aspx
Here's a couple of articles on how to do that, complete with querying an atomic clock for the correct time.
http://www.codeproject.com/KB/IP/ntpclient.aspx
http://www.codeproject.com/KB/datetime/SNTPClient.aspx
要解决 SE_SYSTEMTIME_NAME 权限问题,请尝试创建计划任务来运行您的应用程序并启用“以最高权限运行”。
To get around the SE_SYSTEMTIME_NAME privilege issue, try creating a scheduled task to run your application and enable "Run with highest privileges."