设置系统时间

1 添加timer 和 Datapicker 控件

2 using

using System.Data;
using System.Runtime.InteropServices;

3。code

[DllImport( "Kernel32.dll" )]
public static extern void GetLocalTime(SystemTime st );

[DllImport( "Kernel32.dll" )]
public static extern void SetLocalTime(SystemTime st );

[StructLayout( LayoutKind.Sequential)]
public class SystemTime
{
    public ushort wYear;
    public ushort wMonth;
    public ushort wDayOfWeek;
    public ushort wDay;
    public ushort wHour;
    public ushort wMinute;
    public ushort wSecond;
    public ushort wMilliseconds;
}

4 code

private void timer1_Tick(object sender, System.EventArgs e)
{
    SystemTime st = new SystemTime();
    GetLocalTime(st);
    this.Text="The Date and Time is: " ;
    this.Text=this.Text+st.wHour.ToString()+":";
    this.Text=this.Text+st.wMinute.ToString()+":";
    this.Text=this.Text+st.wSecond.ToString()+".";
    this.Text=this.Text+st.wMilliseconds.ToString();
}

private void Form1_Load(object sender, System.EventArgs e)
{
    this.timer1.Interval=100;
    this.timer1.Enabled=true;
    this.dateTimePicker1.Value=DateTime.Now;
}

//设置按钮
private void button1_Click(object sender, System.EventArgs e)
{
    SystemTime st = new SystemTime();
    st.wYear=(ushort)this.dateTimePicker1.Value.Year;
    st.wMonth=(ushort)this.dateTimePicker1.Value.Month;
    st.wDay=(ushort)this.dateTimePicker1.Value.Day;
    st.wHour=(ushort)this.dateTimePicker1.Value.Hour;
    st.wMinute=(ushort)this.dateTimePicker1.Value.Minute;
    st.wSecond=(ushort)this.dateTimePicker1.Value.Second;
    SetLocalTime(st);
}
Contributors: FHL