c#在WIN7下设置系统时间
2013-03-12 21:39
561 查看
C#设置系统时间:
(1)为了使用DllImportAttribute类,需要引入命名空间:
(2)调用Win32的API,根据需要选用(建议使用SetLocalTime):
(3)自定义类SystemTime用于定义日期时间的结构体。代码如下:
(4)设置时间函数。代码如下:
(5)调用设置时间函数:
(6)注意事项:如果在win7系统下,必须以管理员的身份运行此程序,否则会设置失败!
方法:程序上右键—》属性--》兼容性--》以管理员的身份运行此程序。
(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系统下,必须以管理员的身份运行此程序,否则会设置失败!
方法:程序上右键—》属性--》兼容性--》以管理员的身份运行此程序。
相关文章推荐
- c# 设置系统时间 张宇轩
- C#设置系统日期和时间的代码
- C#设置系统时间的方法实例详解
- 使用C#代码设置系统日期和时间
- C#设置系统时间
- C#设置系统日期和时间
- 用C#设置系统时间和本地时间
- C# 设置CE系统的时间
- C#设置系统时间
- C# 设置系统时间
- CentOS 6.5 、Win7(32位) 双系统 时间同步设置
- C#获取北京时间与设置系统时间
- Qt中设置win7的系统时间
- c# API 设置系统时间
- 嵌入开发(WinCE) 用C#设置系统时间
- 用C#设置系统时间和本地时间
- win7 和 ubuntu16.04 双系统时间同步设置方法
- 系统时间不对导致cookie设置不成功
- Date命令详解——如何设置linux系统时间
- unity c# 获取系统时间