使用C#中的Win32SetSystemTime修改系统日期(仅限日期,无小时,分钟,秒)

时间:2015-03-18 11:59:59

标签: c# date time systemtime system-clock

是否可以设置系统时间(使用Win32SetSystemTime)而不更改小时,分钟和秒(仅限年,月和日)?

这是我的代码。如您所见,我评论了falseData.Hour,falseData.Minute和falseData.Second,因为我不想更改它们。但是,使用此代码,系统时间将在01:00:00自动设置。 手动,我可以更改系统日期而不更改小时,分钟和秒(通过单击任务栏的时钟),但是以编程方式?

任何帮助将不胜感激。 谢谢。马可

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;
using System.Globalization; 
using System.Runtime.InteropServices; 

namespace SysData1_0
{
    public partial class Form1 : Form
    {
        public struct SystemTime
        {
            public ushort Year;
            public ushort Month;
            public ushort DayOfWeek;
            public ushort Day;
            public ushort Hour;
            public ushort Minute;
            public ushort Second;
            public ushort Milliseconds;
        };

        [DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
        public extern static void Win32GetSystemTime(ref SystemTime sysTime);

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

        public Form1()
        {
            InitializeComponent();
        }   

        private void buttonImpostaDataFittizia_Click(object sender, EventArgs e)
        {
            SystemTime falseData = new SystemTime ();
            if (comboBox.SelectedIndex == 0)
            {
                falseData.Year = (ushort)2015;
                falseData.Month = (ushort)3;
            }

            if (comboBox.SelectedIndex == 1)
            {
                falseData.Year = (ushort)2014;
                falseData.Month = (ushort)9;
            }

            //Please, read here 
            falseData.Day = (ushort)1;
            //falseData.Hour = (ushort)10 - 1;
            //falseData.Minute = (ushort)30;
            //falseData.Second = (ushort)30;
            Win32SetSystemTime(ref falseData);

            string Y,M,D;
            Y = Convert.ToString(falseData.Year);
            M = Convert.ToString(falseData.Month);
            D = Convert.ToString(falseData.Day);
            textBoxDataImpostata.Text = D + "/" + M + "/" + Y;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

实际上,这很容易做到,而且你已经拥有了所需的所有方法。只需获取当前时间,然后再将其注入系统:

var nowSystemTime = new SystemTime(); //dummy value so that the code compiles.

Win32GetSystemTime(ref nowSystemTime);

nowSystemTime.Year = (ushort)2015;
nowSystemTime.Month = (ushort)3;

Win32SetSystemTime(ref nowSystemTime);

当然,如果你这样做,请确保在注入系统时间之前花费很多时间,或找到补偿的方法!

答案 1 :(得分:0)

所有SystemTime字段在创建时初始化为其类型的默认值:0表示ushort。

您实际上设置的是与日期相关的值,而不是与时间相关的值,它们保持为0。

我想小时1分与你的时区有关。

您应该执行以下操作:

falseData.Hour = DateTime.Now.Hour
falseData.Minute = DateTime.Now.Minute
falseData.Second = DateTime.Now.Seconds