修改操作系统时间

 

 

    internal class LocalTimeHelper
    {
        [StructLayout(LayoutKind.Sequential)]
        struct SystemTime
        {
            public UInt16 Year;
            public UInt16 Month;
            public UInt16 DayOfWeek;
            public UInt16 Day;
            public UInt16 Hour;
            public UInt16 Minute;
            public UInt16 Second;
            public UInt16 Millisecond;

            public DateTime ToDateTime()
            {
                return new DateTime(Year, Month, Day, Hour, Minute, Second, Millisecond);
            }

            public SystemTime FromDateTime(DateTime value)
            {
                Year = (UInt16)value.Year;
                Month = (UInt16)value.Month;
                Day = (UInt16)value.Day;
                Hour = (UInt16)value.Hour;
                Minute = (UInt16)value.Minute;
                Second = (UInt16)value.Second;
                Millisecond = (UInt16)value.Millisecond;

                return this;
            }

            public static implicit operator DateTime(SystemTime value)
            {
                return value.ToDateTime();
            }

            public static implicit operator SystemTime(DateTime value)
            {
                return new SystemTime().FromDateTime(value);
            }
        }

        [DllImport("kernel32.dll")]
        static extern int SetSystemTime(ref SystemTime systemTime);
        [DllImport("Kernel32.dll")]
        static extern void GetSystemTime(ref SystemTime sysTime);

        public static bool SetSystemLocalTime(DateTime value)
        {
            SystemTime time = value.ToUniversalTime();
            var res = SetSystemTime(ref time);
            return res != 0;
        }

        public static DateTime GetSystemLocalTime()
        {
            var time = new SystemTime();
            GetSystemTime(ref time);
            DateTime res = ((DateTime)time).ToLocalTime();

            return res;
        }
    }

 

posted @ 2015-01-23 17:15  baiqjh  Views(204)  Comments(0Edit  收藏  举报