日期:2014-05-19  浏览次数:20867 次

用c#怎么修改系统的时间啊!
控制台程序要怎么写代码来修改系统的时间啊!请各位大虾帮帮我!

------解决方案--------------------
调用windows API SetLocalTime.
如:
[DllImport( "kernel32.dll ", SetLastError=true)]
public static extern int SetLocalTime (ref SystemTime lpSystemTime);

其中引用的结构定义如下:

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;
}
------解决方案--------------------
利用WINAPI的public static extern bool SetLocalTime( ref SYSTEMTIME Time)实现
public struct 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;

///从System.DateTime转换。
public void FromDateTime(DateTime time)
{
wYear = (ushort)time.Year;
wMonth = (ushort)time.Month;
wDayOfWeek = (ushort)time.DayOfWeek;
wDay = (ushort)time.Day;
wHour = (ushort)time.Hour;
wMinute = (ushort)time.Minute;
wSecond = (ushort)time.Second;
wMilliseconds = (ushort)time.Millisecond;
}

///转换为System.DateTime类型。
public DateTime ToDateTime()
{
return new DateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMilliseconds);
}
/// <summary>
///静态方法。转换为System.DateTime类型。
/// </summary>
/// <param name= "time "> SYSTEMTIME类型的时间。 </param>
/// <returns> </returns>
public static DateTime ToDateTime(SYSTEMTIME time)
{
return time.ToDateTime();
}
}

public class Win32API
{
[DllImport( "Kernel32.dll ")]
public static extern bool SetLocalTime( ref SYSTEMTIME Time );
[DllImport( "Kernel32.dll ")]
public static extern void GetLocalTime(ref SYSTEMTIME Time);
}

public void setTime()//一般
{
/*获得彩屏时间*/
ReceiveCanDataFromJK(0x50);//获得目录


int hour= CanData50[0,0,4]&0x1f;
int minute=CanData50[0,0,5]&0x3f;
int second= CanData50[0,0,6]&0x3f;
int minisecond= (CanData50[0,0,7]&0x7f)*10; //CanData50[0,0,7]百分秒

DateTime t = DateTime.Now; //获取当前时间
t=t.AddHours(hour-t.Hour);
t=t.AddMinutes(minute-t.Minute);
t=t.AddSeconds(second-t.Second);
t=t.AddMilliseconds(minisecond-t.Millisecond);
//转换System.DateTime到SYSTEMTIME
SYSTEMTIME st = new SYSTEMTIME();
st.FromDateTime(t);
//调用Win32 API设置系统时间
Win32API.SetLocalTime(ref st);
}

------解决方案--------------------
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
public class SystemTime
{
public ushort year;
public ushort month;
public ushort dayOfWeek;
public ushort day;
public ushort hour;
public ushort minute;
public ushort second;
public ushort milliseconds;
}
[DllImport( "Kernel32.dll ")]
public static extern void GetSystemTime([In, Out] SystemTime st);