How do I set the Windows system clock to the correct local time using C#?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
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
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 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.
To get around the SE_SYSTEMTIME_NAME privilege issue, try creating a scheduled task to run your application and enable "Run with highest privileges."