This example shows how to set the time and date within the runtime using the InteropServices. We have a number of customers that connect complex plant SCADA systems to our controls system and they often want to make sure all devices on a SCADA network are time synchronized to make alarms easier to troubleshoot.
This code for the most part is copied directly from the MSDN example but I added the using statement to show what namespace was needed. The function SetTime() is just adding 1 hour to the current time but it is easy to adapt to what you want.
Code: Select all
using System.Runtime.InteropServices;
//these dll imports go inside the beginning of the class definition
[DllImport("coredll.dll")]
private extern static void GetSystemTime(ref SYSTEMTIME lpSystemTime);
[DllImport("coredll.dll")]
private extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);
private 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;
}
private void GetTime()
{
// Call the native GetSystemTime method
// with the defined structure.
SYSTEMTIME stime = new SYSTEMTIME();
GetSystemTime(ref stime);
// Show the current time.
MessageBox.Show("Current Time: " + stime.wHour.ToString() + ":" + stime.wMinute.ToString());
}
private void SetTime()
{
// Call the native GetSystemTime method
// with the defined structure.
SYSTEMTIME systime = new SYSTEMTIME();
GetSystemTime(ref systime);
// Set the system clock ahead one hour.
systime.wHour = (ushort)(systime.wHour + 1 % 24);
SetSystemTime(ref systime);
MessageBox.Show("New time: " + systime.wHour.ToString() + ":" + systime.wMinute.ToString());
}
Dan