Welcome Guest ( Login | Register )



All times are UTC - 7 hours [ DST ]



Post new topic Reply to topic  [ 1 post ] 
Author Message
 Post subject: EXAMPLE: Set Time Date / Time Synchronization in runtime
PostPosted: Fri Jan 23, 2015 9:06 am 

Joined: Thu Nov 14, 2013 12:14 pm
Posts: 14

Offline
Lately we have been coming up with a lot of solutions to problems that I thought I should document in case others need to do the same or similar.

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:

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());
}


Cheers,
Dan


 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 1 post ] 

All times are UTC - 7 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  
cron