2013-02-09 72 views
0

我目前正在編寫一個程序,應該按下按鈕時關閉/重新啓動,但是當我按下關機或重新啓動按鈕時,操作立即完成而無需等待(datetimepicker)中指定的時間。ShutDown C#項目

這裏是我的代碼:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace WindowsFormsApplication8 
{ 
    public partial class Form2 : Form 
    { 
     private DateTime tm; 
     public Form2() 
     { 
      InitializeComponent(); 
     } 
     private void button1_Click(object sender, EventArgs e) 
     { 
      if (DateTime.Now.CompareTo(tm) > 0) 
      { 
       Sti(); 
       System.Diagnostics.Process.Start("shutdown", "/s"); 
      } 
      else 
      { 
       MessageBox.Show("your computer will shutdown shortly ...."); 
      } 

     } 
     private void Sti() 
     { 
      if (DateTime.Now.TimeOfDay.CompareTo(tm.TimeOfDay) > 0) 
      { 
       tm = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, tm.Hour, tm.Minute, tm.Second); 
      } 
      else 
      { 
       tm = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, tm.Hour, tm.Minute, tm.Second); 
      } 

     } 

     private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) 
     { 
      this.Show(); 
     } 

     private void notifyIcon1_MouseClick(object sender, MouseEventArgs e) 
     { 

     } 

     private void button2_Click(object sender, EventArgs e) 
     { 
      if (DateTime.Now.CompareTo(tm) >= 0) 
      { 
       Sti(); 
       System.Diagnostics.Process.Start("shutdown", "/r"); 
      } 
      else 
      { 
       MessageBox.Show("your computer will shutdown shortly ...."); 
      } 


     } 
    } 
} 
+0

對於初學者來說穆罕默德你爲什麼不重命名你的'Buttons'多於'Button'或Button'那麼btnRestart和btnShutDown'還有什麼是你傳遞的'Time'的值? '1000 = Sec' – MethodMan 2013-02-09 19:57:32

+0

你在哪裏以及如何設置'tm'? – 2013-02-09 19:58:10

+0

如果你沒有設置tm,那麼它將是1/1/0001 12:00,每次都會小於Now值。 – 2013-02-09 19:59:56

回答

1

使用-t開關shutdown指定一個等待期

shutdown {-r|-s} -t xxx 

其中xxx是秒的等待的秒數。

+0

我需要指定使用datetimepicker關機或重新啓動的時間。 – 2013-02-09 20:05:16

+0

-t需要關機前等待的秒數。這是一個關於關機exe的好鏈接:http://www.codeproject.com/Articles/22718/Shutdown-Remote-Using-Shutdown-exe – 2013-02-09 20:07:40

+0

@MohamedMaher如何這樣的事情:'Process.Start(「關機」, 「/ r -t」+ Math.Floor(tm.Value.Subtract(DateTime.Now).TotalSeconds));'' – romar 2013-02-09 20:27:39