日期类控件的应用--修改系统日期时间
2010-03-27 10:38 Eric.Hu 阅读(639) 评论(0) 收藏 举报平时我们使用 System.DateTime.Now.ToString() 即可获得系统日期时间,
但如何修改系统日期和时间呢,首先我们需要引用一个命名空间 using System.Runtime.InteropServices;
然后定义一个LibWrapDateTime类,引用API函数,代码如下:
代码
1 public class LibWrapDateTime
2 {
3 [DllImportAttribute("Kernel32.dll")]
4 public static extern void GetLocalTime(SystemTime st); //得到当前系统时间方法
5 [DllImportAttribute("Kernel32.dll")]
6 public static extern void SetLocalTime(SystemTime st); //设置系统当前时间
7 }
通过类是实现公共变量:
代码
1 [StructLayoutAttribute(LayoutKind.Sequential)]
2 public class SystemTime
3 {
4 public ushort wYear;
5 public ushort wMonth;
6 public ushort wDateOfWeek;
7 public ushort wDate;
8 public ushort wHour;
9 public ushort wMinute;
10 public ushort wSecond;
11 public ushort wMilliseconds;
12 }
下面我使用了DateTimePicker控件设置时间:
代码
1 private void button2_Click(object sender, EventArgs e) //设置系统当前时间
2 {
3 if (MessageBox.Show("确定修改当前日期时间?", "消息提示", MessageBoxButtons.OK) == DialogResult.OK)
4 {
5 //DateTime year = this.dateTimePicker1.Value;
6 SystemTime MySystemTime = new SystemTime();
7 LibWrapDateTime.GetLocalTime(MySystemTime);
8 MySystemTime.wYear = (ushort)this.dateTimePicker1.Value.Year;
9 MySystemTime.wMonth = (ushort)this.dateTimePicker1.Value.Month;
10 MySystemTime.wDate = (ushort)this.dateTimePicker1.Value.Day;
11 MySystemTime.wHour = (ushort)this.dateTimePicker1.Value.Hour;
12 MySystemTime.wMinute=(ushort)this.dateTimePicker2.Value.Minute;
13 MySystemTime.wSecond = (ushort)this.dateTimePicker2.Value.Second;
14 LibWrapDateTime.SetLocalTime(MySystemTime);
15 button1_Click(null, null);
16 }
17 }
代码下载:/Files/long-gengyun/DateTime.rar
着意耕耘,自有收获。

浙公网安备 33010602011771号