设定机器时间C#

Dus*_*all 5 c# time set

在C#中设置机器时间的最佳方法是什么?

Rob*_*Rob 7

您可能需要使用Win32 API来执行此操作,因为我非常确定框架中没有任何内容:

[StructLayout(LayoutKind.Sequential)] 
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; 
 } 
 [DllImport("kernel32.dll", SetLastError=true)] 
public static extern bool SetSystemTime(ref SYSTEMTIME theDateTime );
Run Code Online (Sandbox Code Playgroud)

PInvoke.net上有一个更完整的例子,代码有点密集,但是一个简单易懂的阅读和理解的摘录是这样的:

SYSTEMTIME st = new SYSTEMTIME();
GetSystemTime(ref st);
// Adds one hour to the time that was retrieved from GetSystemTime
st.wHour = (ushort)(st.wHour + 1 % 24);
var result = SetSystemTime(ref st);
if (result == false)
{
     // Something went wrong
}
else
{
    // The time will now be 1hr later than it was previously
}
Run Code Online (Sandbox Code Playgroud)

相关的特定Win32 API是SetSystemTime,GetSystemTimeSYSTEMTIME结构.

  • 就像抬头一样,您需要管理员权限来设置系统时间.标准用户无法更改时间. (2认同)