Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update the system's date and/or time using .NET

Tags:

c#

.net

vb.net

I am trying to update my system time using the following:

[StructLayout(LayoutKind.Sequential)] 
private struct SYSTEMTIME
{
    public ushort wYear;
    public ushort wMonth;
    public ushort wDayOfWeek;
    public ushort wDay;
    public ushort wHour;
    public ushort wMinute;
    public ushort wSecond;
    public ushort wMilliseconds;
}

[DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
private extern static void Win32GetSystemTime(ref SYSTEMTIME lpSystemTime);

[DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
private extern static bool Win32SetSystemTime(ref SYSTEMTIME lpSystemTime);

public void SetTime()
{
    TimeSystem correctTime = new TimeSystem();
    DateTime sysTime = correctTime.GetSystemTime();
    // Call the native GetSystemTime method
    // with the defined structure.
    SYSTEMTIME systime = new SYSTEMTIME();
    Win32GetSystemTime(ref systime);

    // Set the system clock ahead one hour. 
    systime.wYear = (ushort)sysTime.Year;
    systime.wMonth = (ushort)sysTime.Month;
    systime.wDayOfWeek = (ushort)sysTime.DayOfWeek;
    systime.wDay = (ushort)sysTime.Day;
    systime.wHour = (ushort)sysTime.Hour;
    systime.wMinute = (ushort)sysTime.Minute;
    systime.wSecond = (ushort)sysTime.Second;
    systime.wMilliseconds = (ushort)sysTime.Millisecond;

    Win32SetSystemTime(ref systime);
}

When I debug everything looks good and all the values are correct but when it calles the Win32SetSystemTime(ref systime) th actual time of system(display time) doesn't change and stays the same. The strange part is that when I call the Win32GetSystemTime(ref systime) it gives me the new updated time. Can someone give me some help on this?

like image 305
user62958 Avatar asked Feb 06 '09 19:02

user62958


1 Answers

Part of your problem is that you have a couple of incorrect PInvoke signatures. Most notable SetSystemTime should have a non-void return value. Here is the correct signature

    /// Return Type: BOOL->int
    ///lpSystemTime: SYSTEMTIME*
    [System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint="SetSystemTime")]
    [return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
public static extern  bool SetSystemTime([InAttribute()] ref SYSTEMTIME lpSystemTime) ;

My suspicion is that the lock of a return value messed up the stack and the SetSystemTime function essentially ended up with bad data.

like image 63
JaredPar Avatar answered Oct 15 '22 18:10

JaredPar