[C#][Win32API] SetLocalTime 使用方式

  • 4337
  • 0

摘要:[C#][Win32API] SetLocalTime 使用方式

先在程式中宣告

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool SetSystemTime( ref SystemTime systemTime);

        [DllImport("kernel32.dll", SetLastError=true)]
        public static extern bool SetLocalTime(ref SystemTime systemTime);

        [StructLayout(LayoutKind.Sequential)]
        public struct SystemTime
        {
            [MarshalAs(UnmanagedType.U2)]
            public short wYear;
            [MarshalAs(UnmanagedType.U2)]
            public short wMonth;
            [MarshalAs(UnmanagedType.U2)]
            public short wDayOfWeek;
            [MarshalAs(UnmanagedType.U2)]
            public short wDay;
            [MarshalAs(UnmanagedType.U2)]
            public short wHour;
            [MarshalAs(UnmanagedType.U2)]
            public short wMinute;
            [MarshalAs(UnmanagedType.U2)]
            public short wSecond;
            [MarshalAs(UnmanagedType.U2)]
            public short wMilliseconds;
        }

 

設定本地時間範例

var syncDateTime = DateTime.Now.AddSeconds(10);
var localtime = new SystemTime()
                            {
                                wYear = (short)syncDateTime.Year,
                                wMonth = (short)syncDateTime.Month,
                                wDay = (short)syncDateTime.Day,
                                wDayOfWeek = (short)syncDateTime.DayOfWeek,
                                wHour = (short)syncDateTime.Hour,
                                wMinute = (short)syncDateTime.Minute,
                                wSecond = (short)syncDateTime.Second,
                                wMilliseconds = (short)syncDateTime.Millisecond
                            };

if (!SetLocalTime(ref localtime) )
{
     // 若設定不成功,取得Win32 Error Code,例如取得1314則是權限不夠,要用系統管理員身份執行。
     Console.WriteLine( System.Runtime.InteropServices.Marshal.GetLastWin32Error() );
}