How to set Windows system clock at the correct local time using C #?

How to set Windows system clock at the correct local time using C #?

+8
c # windows windows-xp clock
source share
4 answers

You will need the P / Invoke SetLocalTime function from the Windows API. Declare this in 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; } 

To set the time, you simply initialize an instance of the SYSTEMTIME structure with the appropriate values ​​and call the function. Code example:

 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()); } 

However, note that the calling process must have the appropriate privileges to call this function. In Windows Vista and later, this means that you will need to query the height of the process.


Alternatively, you can use the SetSystemTime function, which allows you to set the time in UTC (Coordinated Universal Time). The same SYSTEMTIME structure is SYSTEMTIME , and the two functions are called the same way.

+10
source share

.NET does not provide a function for this function, but you can use the Win32 API SetSystemTime method (in kernel32.dll). To get the UTC time, you must use the NTP protocol client , and then adjust this time to local time according to your regional settings.

 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); 
+6
source share

Here are some articles on how to do this, complete with requesting the atomic clock for the correct time.

http://www.codeproject.com/KB/IP/ntpclient.aspx

http://www.codeproject.com/KB/datetime/SNTPClient.aspx

+2
source share

To work around the privilege issue of SE_SYSTEMTIME_NAME, try creating a scheduled task to run the application and enable "Run with highest privileges."

0
source share

All Articles