C# 代码如何实现让你的电脑关机,重启,注销,锁定,休眠,睡眠 方法二

简介

本文讲述了用 C# 代码如何实现让你的电脑关机,重启,注销,锁定,休眠,睡眠。

如何实现

首先,使用 using 语句添加我们需要的命名空间:

using System.Diagnostics;
using System.Runtime.InteropServices;

关机

代码如下:

Process.Start("shutdown","/s /t 0");    // 参数 /s 的意思是要关闭计算机
                                        // 参数 /t 0 的意思是告诉计算机 0 秒之后执行命令

重启

代码如下:

Process.Start("shutdown", "/r /t 0"); // 参数 /r 的意思是要重新启动计算机

注销

需要使用 DllImport 的方式在你的类里声明一个 Windows API 函数:

[DllImport(“user32”)]
public static extern bool ExitWindowsEx(uint uFlags, uint dwReason);
然后,使用如下代码就可以实现注销:

ExitWindowsEx(0,0);
锁定

和注销一样也需要声明一个函数:

[DllImport(“user32”)]
public static extern void LockWorkStation();
然后,使用如下代码就可以实现锁定:

LockWorkStation();
休眠和睡眠

同样,还是需要声明一个函数:

[DllImport(“PowrProf.dll”, CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool SetSuspendState(bool hiberate, bool forceCritical, bool disableWakeEvent);
实现休眠,代码如下:

SetSuspendState(true, true, true);
实现睡眠,代码如下:

SetSuspendState(false, true, true);

猜你喜欢

转载自blog.csdn.net/qq_30725967/article/details/89536226