如何使用.NET更新系统的日期和/或时间

use*_*958 8 .net c# vb.net

我正在尝试使用以下内容更新系统时间:

[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);
}
Run Code Online (Sandbox Code Playgroud)

当我调试一切看起来很好并且所有值都是正确的但当它调用Win32SetSystemTime(ref systime)时,系统的实际时间(显示时间)不会改变并保持不变.奇怪的是,当我调用Win32GetSystemTime(ref systime)时,它给了我新的更新时间.有人可以给我一些帮助吗?

Jar*_*Par 6

您的部分问题是您有一些不正确的PInvoke签名.最值得注意的SetSystemTime应具有非void返回值.这是正确的签名

    /// 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) ;
Run Code Online (Sandbox Code Playgroud)

我怀疑是返回值的锁定搞砸了堆栈,而SetSystemTime函数基本上是以坏数据结束的.


Dav*_*ton 4

根据您那里的代码,您不会增加小时。看来您将系统时间设置为与调用 Win32GetSystemTime 时完全相同的时间。

尝试:

systime.wHour = (ushort)(sysTime.Hour + 1);
Run Code Online (Sandbox Code Playgroud)