C#实现windows系统重启和关机的代码详解
作者:lingxiao16888
1、使用shutdown关机命令来实现
using System.Diagnostics;
int time = 3600; //单位为:秒
Process.Start("c:/windows/system32/shutdown.exe", "-s -t "+time);
实现原理,使用系统shutdown命令执行:
强制关机:
shutdown -s -f -t 0
强制重启:
shutdown -r -f -t 0
关于shutdown命令详解:
用法: shutdown [-i | -l | -s | -r | -a] [-f] [-m computername] [-t xx] [-c “comment”] [-d up:xx:yy]
没有参数 显示此消息(与 ? 相同)
-i 显示 GUI 界面,必须是第一个选项
-l 注销(不能与选项 -m 一起使用)
-s 关闭此计算机
-r 关闭并重启动此计算机
-a 放弃系统关机
-m computername 远程计算机关机/重启动/放弃
-t xx 设置关闭的超时为 xx 秒
-c “comment” 关闭注释(最大 127 个字符)
-f 强制运行的应用程序关闭而没有警告
-d [ u ][p]:xx:yy 关闭原因代码
u 是用户代码
p 是一个计划的关闭代码
xx 是一个主要原因代码(小于 256 的正整数)
yy 是一个次要原因代码(小于 65536 的正整数)
-f:强行关闭应用程序
-m 计算机名:控制远程计算机
-i:显示图形用户界面,但必须是Shutdown的第一个选项
-l:注销当前用户
-r:关机并重启
-t时间:设置关机倒计时
-c “消息内容”:输入关机对话框中的消息内容(不能超127个字符)
比如你的电脑要在12:00关机,可以选择“开始→运行”,输入“at 12:00 Shutdown -s",这样,到了12点电脑就会出现“系统关机”对话框,默认有30秒钟的倒计时并提示你保存工作。
如果你想以倒计时的方式关机,可以输入 “Shutdown.exe -s -t 3600",这里表示60分钟后自动关机,“3600"代表60分钟。
一键关机:
1、首先在桌面的空白处单击鼠标右键,新建一个“快捷方式”。
2、在创建快捷方式的“命令行”中输入以下的指令:
“shutdown –s –t 0 ”。(在windows98按此输入“C:windowsRUNDLL32.EXE user,ExitWindows”。)
3、按着鼠标选择“下一步”,在快捷方式的名称栏中输入“一键关机”或其他自己喜欢的名称。
4、之后,你就会在桌面见到一个名为“一键关机”的快捷方式图标,在该图标上单击鼠标右键,选择“属性”,再进入“快捷方式”页,然后在“快速键一栏内随便按选一个功能键(如F1-F12)。建议大家最好选一个平时不常用的功能键,最后按确定退出即可。
Windows系统通过一个名为shutdown.exe的程序来完成关机操作(位置Windows\System32下),一般情况下Windows系统的关机都可以由关机程序 shutdown.exe来实现的,关机的时候调用shutdown.exe。由此可知要阻止强行关机就是要取消对shutdown.exe的调用。
使用C#代码实现控制Windows系统关机、重启和注销的方法,使用.NET和C#.NET,我们可以对当前PC执行关机,重启,注销操作,
.NET Framework中,有一个命名空间System.Diagnostics具有所需的类和方法,从当前PC上运行.NET应用程序来执行这些操作 。一般使用System.Diagnostics.Process.Start()方法来启动shutdown.exe程序。
示例:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//重启电脑
// APIHelper.ExitWindows(UFlag.EWX_REBOOT);//该方法无效
string ss= APIHelper.DOSCommand("shutdown -r -t 2");
MessageBox.Show(ss);
}
private void button2_Click(object sender, EventArgs e)
{
//注销电脑
APIHelper.ExitWindows(UFlag.EWX_LOGOFF);
}
private void button3_Click(object sender, EventArgs e)
{
//关闭电脑
// APIHelper.ExitWindows(UFlag.EWX_SHUTDOWN);//无效
string ss= APIHelper.DOSCommand("shutdown -s -t 2");
MessageBox.Show(ss);
}
private void button4_Click(object sender, EventArgs e)
{
string ss = APIHelper.DOSCommand("shutdown -a");
MessageBox.Show(ss);
}
}
/// <summary>
/// PC操作功能代码
/// </summary>
enum UFlag
{
/// <summary>
/// 强迫终止没有响应的进程
/// </summary>
EWX_FORCE=4,
/// <summary>
/// 注销
/// </summary>
EWX_LOGOFF=0,
/// <summary>
/// 重启
/// </summary>
EWX_REBOOT=2,
/// <summary>
/// 关闭系统
/// </summary>
EWX_SHUTDOWN=1
}
class APIHelper
{
/// <summary>
/// 使用dos命令进行操作
/// </summary>
/// <param name="cmdStr"></param>
/// <returns></returns>
public static string DOSCommand(string cmdStr)
{
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
info.CreateNoWindow =true;//不显示黑窗口
info.FileName = "cmd.exe";
info.RedirectStandardError = true;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
var p = System.Diagnostics.Process.Start(info);
//处理办法1:
//using (System.IO.TextWriter tw= p.StandardInput)
//{
// tw.WriteLine(cmdStr);
//}
//处理办法2:在指令后添加:&exit。
p.StandardInput.WriteLine(cmdStr + "&exit");
p.WaitForExit();
string str = "";
using (System.IO.TextReader tr = p.StandardOutput)
{
str = tr.ReadToEnd();
}
p.Close();
return str;
}
public static int ExitWindows(UFlag flag)
{
return ExitWindowsEx((int)flag, 0);
}
/// <summary>
/// 注销,关闭,重启电脑
/// </summary>
/// <param name="uFlag">要执行的操作</param>
/// <param name="dwReserved">保留值,一般设置为0</param>
/// <returns></returns>
[DllImport("user32.dll")]
extern static int ExitWindowsEx(int uFlag, int dwReserved);
}具体使用方法可参考shutdown.exe的命令行指令。这种方法可在PC上使用,不过当系统为WINCE时,WINCE没有shutdown.exe,所以该方法将不再使用。可用第二种方法。
2、调用WIN32 API来实现
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace TestShutdown
{
class SystemUtil
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TokPriv1Luid
{
public int Count;
public long Luid;
public int Attr;
}
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
[DllImport("advapi32.dll", SetLastError = true)]
internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
[DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool ExitWindowsEx(int flg, int rea);
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
internal const int EWX_LOGOFF = 0x00000000;
internal const int EWX_SHUTDOWN = 0x00000001;
internal const int EWX_REBOOT = 0x00000002;
internal const int EWX_FORCE = 0x00000004;
internal const int EWX_POWEROFF = 0x00000008;
internal const int EWX_FORCEIFHUNG = 0x00000010;
private static void DoExitWin(int flg)
{
bool ok;
TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
ok = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
ok = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid);
ok = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
ok = ExitWindowsEx(flg, 0);
}
public static void Reboot()
{
DoExitWin(EWX_FORCE | EWX_REBOOT); //重启
}
public static void PowerOff()
{
DoExitWin(EWX_FORCE | EWX_POWEROFF); //关机
}
public static void LogoOff()
{
DoExitWin(EWX_FORCE | EWX_LOGOFF); //注销
}
}
}
以上就是C#实现windows系统重启和关机的代码详解的详细内容,更多关于C# windows重启和关机的资料请关注脚本之家其它相关文章!
