/* by josh */

2012年7月30日 星期一

[C#]設定系統時間


//設定格林威治時間
[DllImport("kernel32.dll")]
private extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);

使用上面方式對於使用台北時間的系統而言看到的時間會是設定時間+8小時;
需改為下述方法設定時間才可正確顯示。


//系統設定時間
[DllImport("Kernel32.dll")]
public static extern bool SetLocalTime(ref SYSTEMTIME lpSystemTime);

其中
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;
        }

函式呼叫方式如下:

SYSTEMTIME systime = new SYSTEMTIME();


                // Set config date and time
                systime.wYear = (ushort)(lYear);
                systime.wMonth = (ushort)(lMonth);
                systime.wDay = (ushort)(lDay);
                systime.wHour = (ushort)(lhour);
                systime.wMinute = (ushort)(lMini);
                systime.wSecond = (ushort)(lSec);
                systime.wDayOfWeek = (ushort)(lWeek);
                SetLocalTime(ref systime);