標籤:
簡介
本文講述了用 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 函數:
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); |
用 C# 代碼如何?讓你的電腦關機,重啟,登出,鎖定,休眠,睡眠