C# 通过Win32API设置客户端系统时间

时间:2025-04-09 18:45:40
  • using System;
  • using ;
  • class Program
  • {
  • // 导入SetSystemTime函数
  • [DllImport("", SetLastError = true)]
  • [return: MarshalAs()]
  • static extern bool SetSystemTime(ref SYSTEMTIME time);
  • // SYSTEMTIME结构体
  • [StructLayout()]
  • public 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;
  • // 构造函数,用于方便设置时间
  • public SYSTEMTIME(int year, int month, int day, int hour, int minute, int second)
  • {
  • wYear = (ushort)year;
  • wMonth = (ushort)month;
  • wDay = (ushort)day;
  • wHour = (ushort)hour;
  • wMinute = (ushort)minute;
  • wSecond = (ushort)second;
  • wDayOfWeek = 0; // 通常由系统计算
  • wMilliseconds = 0; // 如果需要,可以设置
  • }
  • }
  • static void Main(string[] args)
  • {
  • // 设置新的系统时间
  • SYSTEMTIME newTime = new SYSTEMTIME(2023, 10, 1, 14, 30, 0);
  • if (!SetSystemTime(ref newTime))
  • {
  • // 处理错误
  • int errorCode = Marshal.GetLastWin32Error();
  • ($"Failed to set system time. Error code: {errorCode}");
  • }
  • else
  • {
  • ("System time set successfully.");
  • }
  • }
  • }
  • 相关文章