C#简单实现关闭计算机、注销和重启电脑的代码

C#演示如何关闭电脑、重启电脑、注销计算机的代码,此前记得发过类似的代码,这一个代码里包括了丰富的注释,或许是C#新手比较喜欢的:

 1 namespace LCRComputer
 2 {
 3     public partial class Frm_Main : Form
 4     {
 5         public Frm_Main()
 6         {
 7             InitializeComponent();
 8         }
 9         [DllImport("user32.dll", EntryPoint = "ExitWindowsEx", CharSet = CharSet.Ansi)]
10         //code www.codesc.net
11         private static extern int ExitWindowsEx(int uFlags, int dwReserved);
12         private void button1_Click(object sender, EventArgs e)
13         {
14             ExitWindowsEx(0, 0);//注销计算机
15         }
16         private void button2_Click(object sender, EventArgs e)
17         {
18             System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
19             myProcess.StartInfo.FileName = "cmd.exe";//启动cmd命令
20             myProcess.StartInfo.UseShellExecute = false;//是否使用系统外壳程序启动进程
21             myProcess.StartInfo.RedirectStandardInput = true;//是否从流中读取
22             myProcess.StartInfo.RedirectStandardOutput = true;//是否写入流
23             myProcess.StartInfo.RedirectStandardError = true;//是否将错误信息写入流
24             myProcess.StartInfo.CreateNoWindow = true;//是否在新窗口中启动进程
25             myProcess.Start();//启动进程
26             myProcess.StandardInput.WriteLine("shutdown -s -t 0");//执行关机命令
27         }
28         private void button3_Click(object sender, EventArgs e)
29         {
30             System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
31             myProcess.StartInfo.FileName = "cmd.exe";//启动cmd命令
32             myProcess.StartInfo.UseShellExecute = false;//是否使用系统外壳程序启动进程
33             myProcess.StartInfo.RedirectStandardInput = true;//是否从流中读取
34             myProcess.StartInfo.RedirectStandardOutput = true;//是否写入流
35             myProcess.StartInfo.RedirectStandardError = true;//是否将错误信息写入流
36             myProcess.StartInfo.CreateNoWindow = true;//是否在新窗口中启动进程
37             myProcess.Start();//启动进程
38             myProcess.StandardInput.WriteLine("shutdown -r -t 0");//执行重启计算机命令
39         }
40     }
41 }

完整的源码例子:C# 注销、关闭和重启计算机的简单完整实例及源码

posted @ 2017-05-22 20:05  jianghuluanke  阅读(8138)  评论(0编辑  收藏  举报