c# - 如何以编程方式加快系统时间?
问题描述
我需要通过为每个(例如)200 毫秒添加随机秒数来加快 PC 系统时间。我试图通过以编程方式查看更改系统日期线程来解决这个问题。
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);
}
}
}
解决方案
应用程序无法更改系统日期,因为它没有管理权限。以管理员身份运行应用程序可以解决问题。
推荐阅读
- java - Spring Boot 项目 jar 作为另一个项目中的依赖项
- java - 导入 jar 文件以像库一样使用但出现错误
- linux - 系统重启时在 Linux 中执行命令
- sql - SQL - 如何为数字创建标志
- java - 如何返回 CompletionStage
Quarkus 中的同步和异步? - tensorflow - 对具有多列的数据集进行 TensorFlow 过滤操作
- c++14 - 为什么我得到随机输出和比接受更多的输出?
- amazon-web-services - 在 Amazon Linux 2 上从源代码构建 AWS 开发工具包
- git-fetch - git fetch 错误:pathspec 与 git 已知的任何文件都不匹配
- javascript - 如何解析这样的json响应(20) [{…}, {…}, {…}, {…}, {…}, …]