To start with, we need to import the library:
[DllImport("kernel32.dll")]
static extern bool SetLocalTime([In] ref SYSTEMTIME lpLocalTime);
Then there is a piece of code from web to change time (http://pinvoke.net/default.aspx/kernel32.SetLocalTime):
using System;
using System.Runtime.InteropServices;
public class MyClass1
{
///
/// SYSTEMTIME structure with some useful methods
///
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 wMilliseconds;
///
/// Convert form System.DateTime
///
///
public void FromDateTime(DateTime time)
{
wYear = (ushort)time.Year;
wMonth = (ushort)time.Month;
wDayOfWeek = (ushort)time.DayOfWeek;
wDay = (ushort)time.Day;
wHour = (ushort)time.Hour;
wMinute = (ushort)time.Minute;
wSecond = (ushort)time.Second;
wMilliseconds = (ushort)time.Millisecond;
}
///
/// Convert to System.DateTime
///
///
public DateTime ToDateTime()
{
return new DateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMilliseconds);
}
///
/// STATIC: Convert to System.DateTime
///
///
///
public static DateTime ToDateTime(SYSTEMTIME time)
{
return time.ToDateTime();
}
}
//SetLocalTime C# Signature
[DllImport("Kernel32.dll")]
public static extern bool SetLocalTime( ref SYSTEMTIME Time );
//Example
private void Add7Days
{
//Get current time and add 7 days to it
DateTime t = DateTime.Now.AddDays(7);;
//Convert to SYSTEMTIME
SYSTEMTIME st = new SYSTEMTIME();
st.FromDateTime(t);
//Call Win32 API to set time
SetLocalTime(ref st);
}
}
No comments:
Post a Comment