C# 修改系统时间
由于手头有一个物联网的触摸屏程序需要提供用户修改系统时间的功能。该功能需要win32的API函数提供支持。具体代码如下:
internal class SystemTimeWin32
{
[DllImport("Kernel32.dll",CharSet = CharSet.Ansi)]
public static extern bool SetSystemTime(ref Systemtime sysTime);
[DllImport("Kernel32.dll")]
public static extern bool SetLocalTime(ref Systemtime sysTime);
[DllImport("Kernel32.dll")]
public static extern void GetSystemTime(ref Systemtime sysTime);
[DllImport("Kernel32.dll")]
public static extern void GetLocalTime(ref Systemtime sysTime);
/// <summary>
/// 时间结构体
/// </summary>
[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;
}
}
消费代码如下:
var localTime = new SystemTimeWin32.Systemtime(){
wYear = 2015,
wMonth = 12,
wDay = 6,
wHour = 10,
wMinute = 23,
wMiliseconds = 56
};
var result = SystemTimeWin32.SetSystemTime(ref localTime);
MessageBox.Show(result.ToString());
运行中发现总是返回false。
经过研究发现原来时我的程序运行在win8系统上需要管理员权限,然后程序作如下配置即可: