C#制作自动关机程序
1、新建C# Window窗体应用程序,并命名为“自动关机”,如下图:

2、设计主窗体,如下:

3、添加如下代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 自动关机
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var str = textBox1.Text;
if (string.IsNullOrEmpty(str)) return;
int time = 0;
if (int.TryParse(str, out time))
{
var startInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe");
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.CreateNoWindow = true;
var myProcess = new System.Diagnostics.Process();
myProcess.StartInfo = startInfo;
myProcess.Start();
myProcess.StandardInput.WriteLine("shutdown -s -t "+time);
}
}
}
}
4、调试运行,设置时间并单击执行,系统会提示在1分钟内将自动关闭(其实,这个1分钟是个约数,无论实际多少,它都提示1分钟),时间到后系统将自动关闭。

1、本文使用控制台命令:shutdown -s -t 时间,实现自动关机。
2、所有控制台的功能都可以通过这种方式内嵌到应用程序中。