web123456

C# Set client system time through Win32API

  • using System;
  • using ;
  • class Program
  • {
  • // Import SetSystemTime function
  • [DllImport("", SetLastError = true)]
  • [return: MarshalAs()]
  • static extern bool SetSystemTime(ref SYSTEMTIME time);
  • // SYSTEMTIME structure
  • [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;
  • // Constructor, used to facilitate time setting
  • 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; // Usually calculated by the system
  • wMilliseconds = 0; // If necessary, you can set it
  • }
  • }
  • static void Main(string[] args)
  • {
  • // Set a new system time
  • SYSTEMTIME newTime = new SYSTEMTIME(2023, 10, 1, 14, 30, 0);
  • if (!SetSystemTime(ref newTime))
  • {
  • // Handle errors
  • int errorCode = Marshal.GetLastWin32Error();
  • ($"Failed to set system time. Error code: {errorCode}");
  • }
  • else
  • {
  • ("System time set successfully.");
  • }
  • }
  • }