详细代码
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace 关机
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Timer1_Tick(null, null);
}
[DllImport("user32.dll", EntryPoint = "ExitWindowsEx", CharSet = CharSet.Ansi)]
private static extern int ExitWindowsEx(int uFlags, int dwReserved);
//注销
private void Btn1_Click(object sender, EventArgs e)
{
ExitWindowsEx(0, 0);//注销计算机
}
//关机
private void Btn2_Click(object sender, EventArgs e)
{
ShutdownOption("shutdown -s -t 0");
}
//重启
private void Btn3_Click(object sender, EventArgs e)
{
ShutdownOption("shutdown -r -t 0");
}
//退出
private void Btn4_Click(object sender, EventArgs e)
{
this.Close();
}
private void Timer1_Tick(object sender, EventArgs e)
{
lbl.Text = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");
}
void ShutdownOption(string code)
{
System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo.FileName = "cmd.exe";//启动cmd命令
myProcess.StartInfo.UseShellExecute = false;//是否使用系统外壳程序启动进程
myProcess.StartInfo.RedirectStandardInput = true;//是否从流中读取
myProcess.StartInfo.RedirectStandardOutput = true;//是否写入流
myProcess.StartInfo.RedirectStandardError = true;//是否将错误信息写入流
myProcess.StartInfo.CreateNoWindow = true;//是否在新窗口中启动进程
myProcess.Start();//启动进程
myProcess.StandardInput.WriteLine(code);//执行重启计算机命令
}
}
}
效果图