【发布时间】:2013-07-06 01:18:33
【问题描述】:
我的程序需要能够更改机器上的 SystemDate。环顾四周后,我找到了这段代码并实现了它,但它似乎根本没有改变日期。它运行的虚拟机关闭了时间同步,所以我知道问题不在于那里。是我犯了一个小错误,还是有更简单的方法来更改系统日期?
[StructLayout(LayoutKind.Sequential)]
private 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;
}
// Return Type: BOOL
[System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint = "SetSystemTime")]
[return:System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
private static extern bool SetSystemTime([InAttribute()] ref SYSTEMTIME lpSystemTime);
public bool SetSystemDateTime(DateTime newDateTime)
{
bool result = false;
try
{
newDateTime = newDateTime.ToUniversalTime();
SYSTEMTIME sysTime = new SYSTEMTIME()
{ wYear = (short)newDateTime.Year /* must be short */,
wMonth = (short)newDateTime.Month,
wDayOfWeek = (short)newDateTime.DayOfWeek,
wDay = (short)newDateTime.Day,
wHour = (short)newDateTime.Hour,
wMinute = (short)newDateTime.Minute,
wSecond = (short)newDateTime.Second,
wMilliseconds = (short)newDateTime.Millisecond };
result = SetSystemTime(ref sysTime);
}
catch (Exception)
{
result = false;
}
return result;
}
【问题讨论】:
-
如果抛出异常,它说明了什么?
-
您是否以管理员身份运行 Visual Studio?
-
@RubensMariuzzo 我不太确定,它还没有抛出异常。
-
@keyboardP 是的,我也在以管理员身份运行程序。
-
正如@keyboardP 所说,您可能需要以管理员身份运行您的应用程序。只有管理员 AFAIK 才允许更改本地系统日期。
标签: c# winapi date datetime time