2013年5月20日 星期一

C# .NET 修改系統時間

依賴系統時間執行不同方法的程式,
測試時可能就需要改變系統時間來確定程式是否有問題。

-參考範例-------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp_ChangeSysTime
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 0;
            do
            {
                Console.WriteLine("請輸入要增加的小時數:");
            } while (!Int32.TryParse(Console.ReadLine(), out x));
            Console.WriteLine("你輸入的小時為:{0}", x);
            SetTime(x);
            Console.WriteLine("現在時間為:");
            GetTime();

            Console.WriteLine("End--------------");
            Console.ReadLine();
            
        }
         [DllImport("Kernel32.dll")]
        private extern static void GetSystemTime(ref SYSTEMTIME lpSystemTime);

         [DllImport("Kernel32.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;
        }

        static void GetTime()
        {
            // Call the native GetSystemTime method
            // with the defined structure.
            SYSTEMTIME stime = new SYSTEMTIME();
            GetSystemTime(ref stime);

            // Show the current time.           
            Console.WriteLine("Current Time: " +
                stime.wHour.ToString() + ":"
                + stime.wMinute.ToString());
        }
        static void SetTime(int i)
        {
            // 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 + i % 24);
            SetSystemTime(ref systime);
            Console.WriteLine("New time: " + systime.wHour.ToString() + ":"
                + systime.wMinute.ToString());
        }

    }
}