当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何使用.NET更新系统的日期和/或时间》经验,为你挑选了1个好方法。

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

[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)时,它给了我新的更新时间.有人可以给我一些帮助吗?



1> JaredPar..:

您的部分问题是您有一些不正确的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函数基本上是以坏数据结束的.

推荐阅读
刘美娥94662
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有