【问题标题】:How to speed up System Time programmatically? [duplicate]如何以编程方式加快系统时间? [复制]
【发布时间】:2019-12-24 08:10:28
【问题描述】:

我需要通过为每(例如)200 毫秒添加一个随机秒数来加快 PC 系统时间。我试图通过查看Change system date programmatically 线程来解决这个问题。

using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace TimeSpeedUp
{
    struct SystemTime
    {
        public ushort Year;
        public ushort Month;
        public ushort DayOfWeek;
        public ushort Day;
        public ushort Hour;
        public ushort Minute;
        public ushort Second;
        public ushort Millisecond;
    }
    class Program
    {
        [DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
        public extern static void Win32GetSystemTime(ref SystemTime sysTime);

        [DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
        public extern static bool Win32SetSystemTime(ref SystemTime sysTime);
        public static Random Random = new Random();

        static void Main(string[] args)
        {
            Timer timer = new Timer(SetTime);
            timer.Change(0, 200);
            while (true)
            {
                ConsoleKeyInfo keyInfo = Console.ReadKey(true);
                if (keyInfo.Key == ConsoleKey.Escape)
                {
                    break;
                }
            }
        }

        public static void SetTime(object obj)
        {
            // Current time
            SystemTime currentTime = new SystemTime();
            Win32GetSystemTime(ref currentTime);
            // Set system date and time
            SystemTime updatedTime = new SystemTime();
            updatedTime.Year = (ushort)currentTime.Year;
            updatedTime.Month = (ushort)currentTime.Month;
            updatedTime.Day = (ushort)currentTime.Day;
            updatedTime.Hour = (ushort)currentTime.Hour;
            updatedTime.Minute = (ushort)currentTime.Minute;
            updatedTime.Second = (ushort)(currentTime.Second + Random.Next(1, 3));
            // Call the unmanaged function that sets the new date and time instantly
            Win32SetSystemTime(ref updatedTime);
        }
    }
}

【问题讨论】:

  • 为什么首先需要这样做?
  • 你能澄清你的问题是什么。这不工作吗?它给你一个例外吗?系统网络是否已连接,“与互联网时间服务器同步”设置是否打开?
  • 这个问题看起来像XY problem。考虑将日期时间逻辑与其他组件分离,例如通过引入接口IDateTimeService,您可以轻松地模拟它。
  • 我更新了我的评论 - 您是否确保“与互联网时间服务器同步”已关闭?
  • 检查返回值并获取错误,如果有的话。

标签: c# .net


【解决方案1】:

应用程序无法更改系统日期,因为它没有管理权限。以管理员身份运行应用程序可以解决问题。

【讨论】:

  • 您的代码不会检查Win32SetSystemTime() 的返回值,这可能是falseMarshal.GetLastWin32Error() 在没有提升运行时产生5 (ERROR_ACCESS_DENIED)。顺便说一句,在您链接到的问题上,有两个答案和三个 cmets 提到需要提升/特殊权限才能设置时间。
  • 虽然您发布的答案确实回答了为什么它不起作用的问题,但我不赞成它,因为正如@BACON 指出的那样,您链接的问题多次提到该解决方案需要提升权限。老实说,我假设你已经排除了这个问题,因为你发布了这个问题并链接到另一个问题。与其回答您自己的问题,不如直接关闭它,因为链接的问题实际上解决了问题。
猜你喜欢
  • 2011-07-30
  • 2018-05-06
  • 2017-01-04
  • 2014-12-30
  • 2016-04-20
  • 1970-01-01
  • 1970-01-01
  • 2016-08-24
  • 1970-01-01
相关资源
最近更新 更多