我正在尝试使用以下内容更新系统时间:
[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); }
当我调试一切看起来很好并且所有值都是正确的但当它调用Win32SetSystemTime(ref systime)时,系统的实际时间(显示时间)不会改变并保持不变.奇怪的是,当我调用Win32GetSystemTime(ref systime)时,它给了我新的更新时间.有人可以给我一些帮助吗?
您的部分问题是您有一些不正确的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) ;
我怀疑是返回值的锁定搞砸了堆栈,而SetSystemTime函数基本上是以坏数据结束的.