MyToolkit函式庫加入設定系統時間

   1: using System.Windows.Forms;
   2: using System.Runtime.InteropServices;

定義資料結構 SystemTime和靜態函式 SetLocalTimeByStr(…)

   1: #region 設定系統時間
   2: [DllImport("Kernel32.dll")]
   3: public static extern bool SetLocalTime(ref SystemTime sysTime);  
   4:  
   5: public struct SystemTime
   6: {
   7:     public ushort wYear;
   8:     public ushort wMonth;
   9:     public ushort wDayOfWeek;
  10:     public ushort wDay;
  11:     public ushort wHour;
  12:     public ushort wMinute;
  13:     public ushort wSecond;
  14:     public ushort wMiliseconds;
  15: }
  16: public static bool SetLocalTimeByStr(string timestr)
  17: {
  18:     bool successful = false;
  19:     SystemTime sysTime = new SystemTime();
  20:     try
  21:     {
  22:         DateTime dt = Convert.ToDateTime(timestr);   // 將字串轉成DateTime格式
  23:  
  24:         sysTime.year = Convert.ToUInt16(dt.Year);
  25:         sysTime.month = Convert.ToUInt16(dt.Month);
  26:         sysTime.day = Convert.ToUInt16(dt.Day);
  27:         sysTime.hour = Convert.ToUInt16(dt.Hour);
  28:         sysTime.min = Convert.ToUInt16(dt.Minute);
  29:         sysTime.sec = Convert.ToUInt16(dt.Second);
  30:         successful = SetLocalTime(ref sysTime);
  31:     }
  32:     catch (Exception e)
  33:     {
  34:         MessageBox.Show("SetLocalTimeByStr Error" + e.Message);
  35:     }
  36:     return successful;
  37: }
  38: #endregion

--------------------------------------------------------------------------------------------------------------------------------------------------------

撰寫一個Windows Form測試剛才的設定系統時間

image

並加入參考MyToolkit.dll

image

button1: 取得目前時間

   1: private void button1_Click(object sender, EventArgs e)
   2: {
   3:      textBox1.Text = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
   4: }

image

button2: 設定系統時間

   1: private void button2_Click(object sender, EventArgs e)
   2: {
   3:     DateTimeTool.SetLocalTimeByStr(textBox1.Text);
   4: }

 

參考資料:

  1. C# 設定系統時間
  2. [C#][Win32API] SetLocalTime 使用方式
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 me1237guy 的頭像
    me1237guy

    天天向上

    me1237guy 發表在 痞客邦 留言(0) 人氣()