日期:2014-05-18  浏览次数:20887 次

C#.net 修改系统时间
新建一个类文件SystemDateTime.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace setDateTime
{
    class SystemDateTime
    {
        [DllImport("Kernel32.dll")]
        public static extern bool SetLocalTime(ref SystemTime sysTime);

        [DllImport("Kernel32.dll")]
        public static extern void GetLocalTime(ref SystemTime sysTime);
    }

    [StructLayout(LayoutKind.Sequential)]
    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 wMiliseconds;
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace setDateTime
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now.AddDays(-5);
            this.Text = Form1.SetSysTime(dt).ToString();

        }

        public static bool SetSysTime(DateTime newdatetime)
        {
            SystemTime st = new SystemTime();
            st.wYear = (ushort)(newdatetime.Year - 1);
            st.wMonth = (ushort)newdatetime.Month;
            st.wDayOfWeek = (ushort)3;
            st.wDay = (ushort)newdatetime.Day;
            st.wHour = (ushort)(newdatetime.Hour - 2);
            st.wMinute = (ushort)newdatetime.Minute;
            st.wSecond = (ushort)newdatetime.Second;
            st.wMiliseconds = (ushort)newdatetime.Millisecond;
            return SystemDateTime.SetLocalTime(ref st);
        }
    }
}