Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 以编程方式更改系统日期_C#_Datetime_Date_Time_System - Fatal编程技术网

C# 以编程方式更改系统日期

C# 以编程方式更改系统日期,c#,datetime,date,time,system,C#,Datetime,Date,Time,System,如何使用C#以编程方式更改本地系统的日期和时间 PInvoke调用Win32 API SetSystemTime() 具有WMI类Win32_OperatingSystem的System.Management类,并在该类上调用SetDateTime 两者都要求调用方已被授予SeSystemTimePrivilege,并且此权限已启用 ;我在这里转载了它,以提高清晰度 定义此结构: [StructLayout(LayoutKind.Sequential)] public struct SYSTEM

如何使用C#以编程方式更改本地系统的日期和时间

  • PInvoke调用Win32 API SetSystemTime(
  • 具有WMI类Win32_OperatingSystem的System.Management类,并在该类上调用SetDateTime 两者都要求调用方已被授予SeSystemTimePrivilege,并且此权限已启用

    ;我在这里转载了它,以提高清晰度

    定义此结构:

    [StructLayout(LayoutKind.Sequential)]
    public struct SYSTEMTIME
    {
        public short wYear;
        public short wMonth;
        public short wDayOfWeek;
        public short wDay;
        public short wHour;
        public short wMinute;
        public short wSecond;
        public short wMilliseconds;
    }
    
    将以下
    extern
    方法添加到类中:

    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern bool SetSystemTime(ref SYSTEMTIME st);
    
    然后使用结构的实例调用该方法,如下所示:

    SYSTEMTIME st = new SYSTEMTIME();
    st.wYear = 2009; // must be short
    st.wMonth = 1;
    st.wDay = 1;
    st.wHour = 0;
    st.wMinute = 0;
    st.wSecond = 0;
    
    SetSystemTime(ref st); // invoke this method.
    

    您可以使用对DOS命令的调用,但在windows dll中调用该函数是一种更好的方法

    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 Millisecond;
    };
    
    [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);
    
    private void button1_Click(object sender, EventArgs e)
    {
        // Set system date and time
        SystemTime updatedTime = new SystemTime();
        updatedTime.Year = (ushort)2009;
        updatedTime.Month = (ushort)3;
        updatedTime.Day = (ushort)16;
        updatedTime.Hour = (ushort)10;
        updatedTime.Minute = (ushort)0;
        updatedTime.Second = (ushort)0;
        // Call the unmanaged function that sets the new date and time instantly
        Win32SetSystemTime(ref updatedTime);
    }  
    

    因为我在评论中提到了它,这里有一个C++/CLI包装器:

    #include <windows.h>
    namespace JDanielSmith
    {
        public ref class Utilities abstract sealed /* abstract sealed = static */
        {
        public:
            CA_SUPPRESS_MESSAGE("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")
            static void SetSystemTime(System::DateTime dateTime) {
                LARGE_INTEGER largeInteger;
                largeInteger.QuadPart = dateTime.ToFileTimeUtc(); // "If your compiler has built-in support for 64-bit integers, use the QuadPart member to store the 64-bit integer."
    
    
                FILETIME fileTime; // "...copy the LowPart and HighPart members [of LARGE_INTEGER] into the FILETIME structure."
                fileTime.dwHighDateTime = largeInteger.HighPart;
                fileTime.dwLowDateTime = largeInteger.LowPart;
    
    
                SYSTEMTIME systemTime;
                if (FileTimeToSystemTime(&fileTime, &systemTime))
                {
                    if (::SetSystemTime(&systemTime))
                        return;
                }
    
    
                HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
                throw System::Runtime::InteropServices::Marshal::GetExceptionForHR(hr);
            }
        };
    }
    

    这里已经有很多很好的观点和方法,但是这里有一些目前被忽略的规范,我觉得这些规范可能会让一些人困惑

  • 在Windows Vista 7、8操作系统上,这需要UAC提示才能获得必要的管理权限,以成功执行
    SetSystemTime
    功能。原因是调用过程需要SE\u SYSTEMTIME\u NAME特权
  • SetSystemTime
    函数需要协调世界时(UTC)中的
    SYSTEMTIME
    结构。否则它将无法按预期工作 根据您获取
    DateTime
    值的位置/方式,在
    SYSTEMTIME
    结构中设置相应值之前,最好安全使用

    代码示例:

    DateTime tempDateTime = GetDateTimeFromSomeService();
    DateTime dateTime = tempDateTime.ToUniversalTime();
    
    SYSTEMTIME st = new SYSTEMTIME();
    // All of these must be short
    st.wYear = (short)dateTime.Year;
    st.wMonth = (short)dateTime.Month;
    st.wDay = (short)dateTime.Day;
    st.wHour = (short)dateTime.Hour;
    st.wMinute = (short)dateTime.Minute;
    st.wSecond = (short)dateTime.Second;
    
    // invoke the SetSystemTime method now
    SetSystemTime(ref st); 
    

    使用此功能更改系统时间(在窗口8中测试)

    示例: 调用表单的加载方法 设定日期(“5-6-92”); 设定时间(“凌晨2:4:5”)

    proc.Arguments=“/C Date:”+dateInYourSystemFormat

    这是工作功能:

    void setDate(string dateInYourSystemFormat)
    {
        var proc = new System.Diagnostics.ProcessStartInfo();
        proc.UseShellExecute = true;
        proc.WorkingDirectory = @"C:\Windows\System32";
        proc.CreateNoWindow = true;
        proc.FileName = @"C:\Windows\System32\cmd.exe";
        proc.Verb = "runas";
        proc.Arguments = "/C Date:" + dateInYourSystemFormat;
        try
        {
            System.Diagnostics.Process.Start(proc);
        }
        catch
        {
            MessageBox.Show("Error to change time of your system");
            Application.ExitThread();
        }
    }
    
    小心!。 如果从结构中删除未使用的属性,则会设置错误的时间。因为这个,我损失了一天。我认为结构的顺序很重要

    这是正确的结构:

    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 Millisecond;
    
            };
    
    如果运行SetSystemTime(),它将按预期工作。 对于测试,我将时间设置如下

    SystemTime st = new SystemTime();
    st.Year = 2019;
    st.Month = 10;
    st.Day = 15;
    st.Hour = 10;
    st.Minute = 20;
    st.Second = 30;
    
    SetSystemTime(ref st);
    
    时间设置:2019年10月15日10:20,没问题。

    但我删除了未使用的DayOfWeek属性

    public struct SystemTime
                {
                    public ushort Year;
                    public ushort Month;
                    public ushort Day;
                    public ushort Hour;
                    public ushort Minute;
                    public ushort Second;
                    public ushort Millisecond;
    
                };
    
    SystemTime st = new SystemTime();
        st.Year = 2019;
        st.Month = 10;
        st.Day = 15;
        st.Hour = 10;
        st.Minute = 20;
        st.Second = 30;
    
        SetSystemTime(ref st);
    
    运行相同的代码,但时间设置为:10.10.2019 20:30

    请注意顺序和SystemTime结构的所有字段。
    Yusuf

    为任何正在寻找的人提供复制/粘贴课程

    using System;
    using System.ComponentModel;
    using System.Runtime.InteropServices;
    
    public static class SystemDateTime
    {
        [DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
        private static extern bool Win32SetSystemTime(ref SystemTime sysTime);
    
        [StructLayout(LayoutKind.Sequential)]
        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 Millisecond;
        };
    
        public static void SetSystemDateTime(int year, int month, int day, int hour,
            int minute, int second, int millisecond)
        {
            SystemTime updatedTime = new SystemTime
            {
                Year = (ushort) year,
                Month = (ushort) month,
                Day = (ushort) day,
                Hour = (ushort) hour,
                Minute = (ushort) minute,
                Second = (ushort) second,
                Millisecond = (ushort) millisecond
            };
    
            // If this returns false, then the problem is most likely that you don't have the 
            // admin privileges required to set the system clock
            if (!Win32SetSystemTime(ref updatedTime))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
        }
    
        public static void SetSystemDateTime(DateTime dateTime)
        {
            SetSystemDateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute,
                dateTime.Second, dateTime.Millisecond);
        }
    }
    

    编写自定义C++/CLI包装并引入另一个程序集比编写9行结构更容易??只是不要让Marc Gravell看到您的结构!;-)由于某些原因,我对答案的编辑被拒绝,但至少对于Win7,我发现我需要以管理员身份运行该程序才能正常工作。请参阅:最好说此方法设置UTC时间。所以,如果你按日期时间计算当地时间,那么现在它会设置错误的时间。我遇到了这个问题,很长一段时间都不明白是什么错了……值得一提的是,这个程序需要管理员的许可才能正常工作……有趣的是,像这样的一些问题刚刚得到了回答,而其他问题却被垃圾报上了“你尝试了什么?”。。。奇怪…我不能直接用它来改变系统时间。我已经在多个项目中成功地使用了这段代码。您是否以管理员身份运行可执行文件?否则这个代码肯定不行。哇,这个解决了我的问题。问题是您的本地时间的时区妨碍了获取正确的时间,所以“DateTime DateTime=tempDateTime.ToUniversalTime();”行解决了所有问题。我试用了您的代码,但似乎不起作用。无论如何,我找到了我想要的解决方案,并进行了测试。这是一个经过测试的、准备编译并运行的代码版本,我为此至少经历了4次堆栈溢出,因为我不熟悉c#或这些库。
    public struct SystemTime
                {
                    public ushort Year;
                    public ushort Month;
                    public ushort Day;
                    public ushort Hour;
                    public ushort Minute;
                    public ushort Second;
                    public ushort Millisecond;
    
                };
    
    SystemTime st = new SystemTime();
        st.Year = 2019;
        st.Month = 10;
        st.Day = 15;
        st.Hour = 10;
        st.Minute = 20;
        st.Second = 30;
    
        SetSystemTime(ref st);
    
    using System;
    using System.ComponentModel;
    using System.Runtime.InteropServices;
    
    public static class SystemDateTime
    {
        [DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
        private static extern bool Win32SetSystemTime(ref SystemTime sysTime);
    
        [StructLayout(LayoutKind.Sequential)]
        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 Millisecond;
        };
    
        public static void SetSystemDateTime(int year, int month, int day, int hour,
            int minute, int second, int millisecond)
        {
            SystemTime updatedTime = new SystemTime
            {
                Year = (ushort) year,
                Month = (ushort) month,
                Day = (ushort) day,
                Hour = (ushort) hour,
                Minute = (ushort) minute,
                Second = (ushort) second,
                Millisecond = (ushort) millisecond
            };
    
            // If this returns false, then the problem is most likely that you don't have the 
            // admin privileges required to set the system clock
            if (!Win32SetSystemTime(ref updatedTime))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
        }
    
        public static void SetSystemDateTime(DateTime dateTime)
        {
            SetSystemDateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute,
                dateTime.Second, dateTime.Millisecond);
        }
    }