C#,定时自动关机

一直想找一个可以自己实现定时自动关机的软件,辛辛苦苦在网上找了一个,结果搞了几次之后竟然要收费,闲来自己也写一个试试。
 
这是一个很小的winform应用,使用VS2008+.NET 3.5环境开发,要在XP系统且安装了.NET3.5的机器上才能使用,期待后续版本的升级。
 
本文着重介绍关机操作和定时的实现,其余部分不再详述。
-------------------------------
--AutoShutDown V1.0
-------------------------------
自动关机部分的实现:
Process proc = new Process();
proc.StartInfo.FileName = "cmd.exe";//start the command line
proc.StartInfo.UseShellExecute = false;//do not use shell mode instead by programme mode
proc.StartInfo.RedirectStandardError = true;//re-direct IO
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.CreateNoWindow = true;//do not creat a form
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
//BLANK is a const var with " "
string commandLine = String.Empty;
switch (option)
{
       case Program.OptionType.isCancel:
              commandLine += @"shutdown /a";
              break;
       case Program.OptionType.isLogoff:
              commandLine += @"shutdown /f /l /t" + BLANK + interval;
              break;
       case Program.OptionType.isRestart:
              commandLine += @"shutdown /f /r /t" + BLANK + interval;
               break;
       case Program.OptionType.isShutdown:
              commandLine += @"shutdown /f /s /t" + BLANK + interval;
              break;
       }
       proc.StandardInput.WriteLine(commandLine);
新建一个Process对象,启动命令行窗口,并使用不显示窗口的模式,然后标记命令行命令进行操作。
常用的命令行操作有:

-a or /a

Abort/取消所有shutdown操作

-l or /l

Log off

-r or /r

重新启动 restart

-s or /s

Shutdown 关闭计算机

-t or /t xx

xx秒后进行操作

-----------------------------------------------
winform定时器的实现:
使用timer控件的Tick事件来实现,事件代码如下。
private void timer_CountDown_Tick(object sender, EventArgs e)
{
      if ((intervalSeconds - secondsFlush) == 0)
     {
          timer_CountDown.Stop();
          toolStripStatusLabel_ShowText.Visible = false;
          toolStripStatusLabel_TimeLeft.Visible = false;
          ControlSpengding();
     }
     else
     {
          secondsFlush += 1;
          toolStripStatusLabel_TimeLeft.Text = (intervalSeconds - secondsFlush).ToString();
     }
}
原文地址:https://www.cnblogs.com/skyshenwei/p/1677009.html