C#設置系統日期和時間的代碼分享,使用C#代碼設置系統日期和時間的程式開發步驟如下: (1)為了使用DllImportAttribute類,需要引入命名空間: using System.Runtime.InteropServices; (2)自定義類SetSystemDateTime用於設置系統時間
C#設置系統日期和時間的代碼分享,使用C#代碼設置系統日期和時間的程式開發步驟如下: (1)為了使用DllImportAttribute類,需要引入命名空間: using System.Runtime.InteropServices; (2)自定義類SetSystemDateTime用於設置系統時間。代碼如下: public class SetSystemDateTime { [DllImportAttribute( "Kernel32.dll" )] public static extern void GetLocalTime(SystemTime st ) ; [DllImportAttribute( "Kernel32.dll" )] public static extern void SetLocalTime(SystemTime st ) ; } (3)自定義類SystemTime用於定義日期時間類。代碼如下: [StructLayoutAttribute( LayoutKind.Sequential)] public class SystemTime { public ushort vYear; public ushort vMonth; public ushort vDayOfWeek; public ushort vDay; public ushort vHour; public ushort vMinute; public ushort vSecond; } (4)選擇一個時間,單擊“設置系統新日期時間”按鈕,在該按鈕的Click事件下,調用自定義類SetSystemDateTime和SystemTime,修改當前系統日期時間。代碼如下: private void button2_Click(object sender, EventArgs e) { //設置系統當前日期時間 if (MessageBox.Show("您真的確定更改系統當前日期和時間嗎?", "信息提示", MessageBoxButtons.OK) == DialogResult.OK) { DateTime Year = this.dateTimePicker1.Value; SystemTime MySystemTime = new SystemTime(); SetSystemDateTime.GetLocalTime(MySystemTime); MySystemTime.vYear = (ushort)this.dateTimePicker1.Value.Year; MySystemTime.vMonth = (ushort)this.dateTimePicker1.Value.Month; MySystemTime.vDay = (ushort)this.dateTimePicker1.Value.Day; MySystemTime.vHour = (ushort)this.dateTimePicker2.Value.Hour; MySystemTime.vMinute = (ushort)this.dateTimePicker2.Value.Minute; MySystemTime.vSecond = (ushort)this.dateTimePicker2.Value.Second; SetSystemDateTime.SetLocalTime(MySystemTime); } }