簡介
本文講述了用 C# 代碼如何實現讓你的電腦關機,重啟,注銷,鎖定,休眠,睡眠。
如何實現
首先,使用 using 語句添加我們需要的命名空間:
using System.Diagnostics; |
using System.Runtime.InteropServices; |
關機
代碼如下:
Process.Start("shutdown","/s /t 0"); |
重啟
代碼如下:
Process.Start("shutdown", "/r /t 0"); |
注銷
需要使用 DllImport 的方式在你的類里聲明一個 Windows API 函數:
public static extern bool ExitWindowsEx(uint uFlags, uint dwReason); |
然后,使用如下代碼就可以實現注銷:
鎖定
和注銷一樣也需要聲明一個函數:
public static extern void 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); |