开发者

Set machine time C#

What is the best way 开发者_开发技巧to set the machine time in C#?


You'll probably need to use the Win32 API to do this, as I'm fairly sure there's nothing baked into the framework:

[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 );

There's a fuller example at PInvoke.net, the code's a bit dense, but a simple excerpt that's fairly plain to read and understand is this:

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
}

The relevant specific Win32 API's are SetSystemTime, GetSystemTime and the SYSTEMTIME structure.


Microsoft.VisualBasic.DateAndTime.TimeOfDay = dateTime;

Add a reference of Microsoft.VisualBasic to you project Please let me know if any issue

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜