您的位置:首页 > 编程语言 > C#

c#在WIN7下设置系统时间

2013-03-12 21:39 561 查看
C#设置系统时间:

(1)为了使用DllImportAttribute类,需要引入命名空间:

using System.Runtime.InteropServices;


(2)调用Win32的API,根据需要选用(建议使用SetLocalTime):

[DllImport("Kernel32.dll")]
public static extern bool SetSystemTime(ref SystemTime sysTime);

[DllImport("Kernel32.dll")]
public static extern void GetSystemTime(ref SystemTime sysTime);

[DllImport("Kernel32.dll")]
public static extern bool SetLocalTime(ref SystemTime sysTime);

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


(3)自定义类SystemTime用于定义日期时间的结构体。代码如下:

[StructLayout(LayoutKind.Sequential)]
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 wMiliseconds;
}


(4)设置时间函数。代码如下:

/// <summary>
/// 设置本机时间
/// </summary>
public static bool SyncTime(DateTime currentTime)
{
bool flag = false;
SystemTime sysTime = new SystemTime();
sysTime.wYear = Convert.ToUInt16(currentTime.Year);
sysTime.wMonth = Convert.ToUInt16(currentTime.Month);
sysTime.wDay = Convert.ToUInt16(currentTime.Day);
sysTime.wHour = Convert.ToUInt16(currentTime.Hour);
sysTime.wMinute = Convert.ToUInt16(currentTime.Minute);
sysTime.wSecond = Convert.ToUInt16(currentTime.Second);
try
{
flag = SetLocalTime(ref sysTime);
}
catch (Exception e)
{
Console.WriteLine("SetSystemDateTime函数执行异常" + e.Message);
}
return flag;
}


(5)调用设置时间函数:

DateTime date = new DateTime(2013, 3, 11);
TimeParser.SyncTime(date);


(6)注意事项:如果在win7系统下,必须以管理员的身份运行此程序,否则会设置失败!

方法:程序上右键—》属性--》兼容性--》以管理员的身份运行此程序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: