C#實現(xiàn)windows系統(tǒng)重啟和關(guān)機的代碼詳解
1、使用shutdown關(guān)機命令來實現(xiàn)
using System.Diagnostics;
int time = 3600; //單位為:秒
Process.Start("c:/windows/system32/shutdown.exe", "-s -t "+time);
實現(xiàn)原理,使用系統(tǒng)shutdown命令執(zhí)行:
強制關(guān)機:
shutdown -s -f -t 0
強制重啟:
shutdown -r -f -t 0
關(guān)于shutdown命令詳解:
用法: shutdown [-i | -l | -s | -r | -a] [-f] [-m computername] [-t xx] [-c “comment”] [-d up:xx:yy]
沒有參數(shù) 顯示此消息(與 ? 相同)
-i 顯示 GUI 界面,必須是第一個選項
-l 注銷(不能與選項 -m 一起使用)
-s 關(guān)閉此計算機
-r 關(guān)閉并重啟動此計算機
-a 放棄系統(tǒng)關(guān)機
-m computername 遠程計算機關(guān)機/重啟動/放棄
-t xx 設(shè)置關(guān)閉的超時為 xx 秒
-c “comment” 關(guān)閉注釋(最大 127 個字符)
-f 強制運行的應(yīng)用程序關(guān)閉而沒有警告
-d [ u ][p]:xx:yy 關(guān)閉原因代碼
u 是用戶代碼
p 是一個計劃的關(guān)閉代碼
xx 是一個主要原因代碼(小于 256 的正整數(shù))
yy 是一個次要原因代碼(小于 65536 的正整數(shù))
-f:強行關(guān)閉應(yīng)用程序
-m 計算機名:控制遠程計算機
-i:顯示圖形用戶界面,但必須是Shutdown的第一個選項
-l:注銷當前用戶
-r:關(guān)機并重啟
-t時間:設(shè)置關(guān)機倒計時
-c “消息內(nèi)容”:輸入關(guān)機對話框中的消息內(nèi)容(不能超127個字符)
比如你的電腦要在12:00關(guān)機,可以選擇“開始→運行”,輸入“at 12:00 Shutdown -s",這樣,到了12點電腦就會出現(xiàn)“系統(tǒng)關(guān)機”對話框,默認有30秒鐘的倒計時并提示你保存工作。
如果你想以倒計時的方式關(guān)機,可以輸入 “Shutdown.exe -s -t 3600",這里表示60分鐘后自動關(guān)機,“3600"代表60分鐘。
一鍵關(guān)機:
1、首先在桌面的空白處單擊鼠標右鍵,新建一個“快捷方式”。
2、在創(chuàng)建快捷方式的“命令行”中輸入以下的指令:
“shutdown –s –t 0 ”。(在windows98按此輸入“C:windowsRUNDLL32.EXE user,ExitWindows”。)
3、按著鼠標選擇“下一步”,在快捷方式的名稱欄中輸入“一鍵關(guān)機”或其他自己喜歡的名稱。
4、之后,你就會在桌面見到一個名為“一鍵關(guān)機”的快捷方式圖標,在該圖標上單擊鼠標右鍵,選擇“屬性”,再進入“快捷方式”頁,然后在“快速鍵一欄內(nèi)隨便按選一個功能鍵(如F1-F12)。建議大家最好選一個平時不常用的功能鍵,最后按確定退出即可。
Windows系統(tǒng)通過一個名為shutdown.exe的程序來完成關(guān)機操作(位置Windows\System32下),一般情況下Windows系統(tǒng)的關(guān)機都可以由關(guān)機程序 shutdown.exe來實現(xiàn)的,關(guān)機的時候調(diào)用shutdown.exe。由此可知要阻止強行關(guān)機就是要取消對shutdown.exe的調(diào)用。
使用C#代碼實現(xiàn)控制Windows系統(tǒng)關(guān)機、重啟和注銷的方法,使用.NET和C#.NET,我們可以對當前PC執(zhí)行關(guān)機,重啟,注銷操作,
.NET Framework中,有一個命名空間System.Diagnostics具有所需的類和方法,從當前PC上運行.NET應(yīng)用程序來執(zhí)行這些操作 。一般使用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)
{
//關(guān)閉電腦
// 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>
/// 強迫終止沒有響應(yīng)的進程
/// </summary>
EWX_FORCE=4,
/// <summary>
/// 注銷
/// </summary>
EWX_LOGOFF=0,
/// <summary>
/// 重啟
/// </summary>
EWX_REBOOT=2,
/// <summary>
/// 關(guān)閉系統(tǒng)
/// </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>
/// 注銷,關(guān)閉,重啟電腦
/// </summary>
/// <param name="uFlag">要執(zhí)行的操作</param>
/// <param name="dwReserved">保留值,一般設(shè)置為0</param>
/// <returns></returns>
[DllImport("user32.dll")]
extern static int ExitWindowsEx(int uFlag, int dwReserved);
}具體使用方法可參考shutdown.exe的命令行指令。這種方法可在PC上使用,不過當系統(tǒng)為WINCE時,WINCE沒有shutdown.exe,所以該方法將不再使用??捎玫诙N方法。
2、調(diào)用WIN32 API來實現(xiàn)
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); //關(guān)機
}
public static void LogoOff()
{
DoExitWin(EWX_FORCE | EWX_LOGOFF); //注銷
}
}
}
以上就是C#實現(xiàn)windows系統(tǒng)重啟和關(guān)機的代碼詳解的詳細內(nèi)容,更多關(guān)于C# windows重啟和關(guān)機的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Unity的IPreprocessBuild實用案例深入解析
這篇文章主要為大家介紹了Unity的IPreprocessBuild實用案例深入解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05
C#動態(tài)創(chuàng)建Access數(shù)據(jù)庫及表的方法
這篇文章主要介紹了C#動態(tài)創(chuàng)建Access數(shù)據(jù)庫及表的方法,以實例形式分析了創(chuàng)建access數(shù)據(jù)庫及在access數(shù)據(jù)庫中建表的完整過程,是非常實用的技巧,需要的朋友可以參考下2014-12-12
C# Winform DataGridView數(shù)據(jù)刷新問題的解決辦法
DataGridView 是比較常用的表格控件,在 DataGridView 中顯示數(shù)據(jù), 一般使用 dataGridView1.DataSource = 數(shù)據(jù)源,來綁定數(shù)據(jù),那么如何做到及時刷新數(shù)據(jù)呢,本文給大家介紹了C# Winform DataGridView數(shù)據(jù)刷新問題的解決辦法,需要的朋友可以參考下2024-09-09
總結(jié)C#刪除字符串數(shù)組中空字符串的幾種方法
C#中要如何才能刪除一個字符串數(shù)組中的空字符串呢?下面的文章會介紹多種方式來實現(xiàn)清除數(shù)組中的空字符串,以及在.net中將字符串數(shù)組中字符串為空的元素去除。2016-08-08

