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); } }
本文来自: IT知道网(http://www.itwis.com) 详细出处参考:http://www.itwis.com/html/net/c/20100706/8681.html
|
请发表评论