C#實現(xiàn)控制電腦注銷,關(guān)機(jī)和重啟
實現(xiàn)目標(biāo)
通過C#實現(xiàn)電腦的注銷、關(guān)機(jī)、重啟功能
知識點
本案例涉及的知識點包含:Process、Shell32.dll、User32.dll、Struct數(shù)據(jù)結(jié)構(gòu)。
Process
本案例主要通過Process類調(diào)用cmd.exe.使用shell命令實現(xiàn)電機(jī)的關(guān)機(jī)和重啟。
用到的屬性和方法有:StartInfo(屬性) 和Start(方法)。
StartInfo.FileName
獲取或設(shè)置要啟動的應(yīng)用程序或文檔。
Process.StartInfo.FileName Process.StartInfo.FileName = "cmd.exe"
StartInfo.UseShellExecute
如果應(yīng)在啟動進(jìn)程時使用 shell,則為 true;如果直接從可執(zhí)行文件創(chuàng)建進(jìn)程,則為 false。 默認(rèn)值為true。
以下場景值為True:
需要打開文檔、媒體、網(wǎng)頁文件等 需要打開 Url 需要打開腳本執(zhí)行 需要打開計算機(jī)上環(huán)境變量中路徑中的程序
以下場景值為False:
需要明確執(zhí)行一個已知的程序 需要重定向輸入和輸出
UseShellExecute = true 調(diào)用的是 ShellExecute
UseShellExecute = false 調(diào)用的是 CreateProcess
Process.StartInfo.UseShellExecute Process.StartInfo.UseShellExecute = false
StartInfo.RedirectStandardInput
獲取用于寫入應(yīng)用程序輸入的流。
如果應(yīng)從 StandardInput 讀取輸入,則為 true;否則為 false。 默認(rèn)值為 false。
A Process 可以從其標(biāo)準(zhǔn)輸入流(通常是鍵盤)讀取輸入文本。 通過重定向 StandardInput 流,可以編程方式指定進(jìn)程的輸入。 例如,你可以從指定文件的內(nèi)容或從另一個應(yīng)用程序的輸出中提供文本,而不是使用鍵盤輸入。
StartInfo.RedirectStandardOutput
獲取或設(shè)置指示是否將應(yīng)用程序的文本輸出寫入 StandardOutput 流中的值。
如果輸出應(yīng)寫入 StandardOutput,則為 true;否則為 false。 默認(rèn)值為 false。
Process當(dāng)將文本寫入其標(biāo)準(zhǔn)流時,該文本通常顯示在主機(jī)上。 通過設(shè)置為RedirectStandardOutputtrue重定向StandardOutput流,可以操作或取消進(jìn)程的輸出。 例如,可以篩選文本、以不同的方式設(shè)置格式,或?qū)⑤敵鰧懭肟刂婆_和指定的日志文件。
// Run "csc.exe /r:System.dll /out:sample.exe stdstr.cs". UseShellExecute is false because we're specifying // an executable directly and in this case depending on it being in a PATH folder. By setting // RedirectStandardOutput to true, the output of csc.exe is directed to the Process.StandardOutput stream // which is then displayed in this console window directly. using (Process compiler = new Process()) { compiler.StartInfo.FileName = "csc.exe"; compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs"; compiler.StartInfo.UseShellExecute = false; compiler.StartInfo.RedirectStandardOutput = true; compiler.Start(); Console.WriteLine(compiler.StandardOutput.ReadToEnd()); compiler.WaitForExit(); }
StartInfo.RedirectStandardError
獲取或設(shè)置指示是否將應(yīng)用程序的錯誤輸出寫入 StandardError 流中的值。
如果錯誤輸出應(yīng)寫入 StandardError,則為 true;否則為 false。 默認(rèn)值為 false。
Process當(dāng)將文本寫入其標(biāo)準(zhǔn)錯誤流時,該文本通常顯示在主機(jī)上。 通過重定向 StandardError 流,可以操作或禁止進(jìn)程的錯誤輸出。 例如,可以篩選文本、以不同的方式設(shè)置格式,或?qū)⑤敵鰧懭肟刂婆_和指定的日志文件.
StartInfo.CreateNoWindow
獲取或設(shè)置指示是否在新窗口中啟動該進(jìn)程的值。
如果應(yīng)啟動進(jìn)程而不創(chuàng)建包含它的新窗口,則為true ;否則為 false。 默認(rèn)值為 false。
對控制面板窗口有效,與 UseShellExecute 結(jié)合使用。
UseShellExecute = true 時此值無效,為正常方式啟動。
UseShellExecute = false;CreateNoWindow = true 時,控制面板窗口不會顯示。這種方式下無法通過窗口關(guān)閉進(jìn)程,所以運行的進(jìn)程最好是可以自己運行完關(guān)閉的,不然需要到任務(wù)管理器中關(guān)閉。
Start
啟動進(jìn)程資源并將其與 Process 組件關(guān)聯(lián)。
StandardInput.WriteLine(cmd)
獲取用于寫入應(yīng)用程序輸入的流。
StreamWriter,可用于寫入應(yīng)用程序的標(biāo)準(zhǔn)輸入流。
shell32.dll
public static extern bool SendMessage(IntPtr hwdn, int wMsg, int mParam, int lParam); //從exe\dll\ico文件中獲取指定索引或ID號的圖標(biāo)句柄 [DllImport("shell32.dll", EntryPoint = "ExtractIcon")] //獲取文件圖標(biāo)的API函數(shù) [DllImport("shell32.dll", EntryPoint = "SHGetFileInfo")] public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttribute, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint Flags); //從exe\dll\ico文件中生成圖標(biāo)句柄數(shù)組 [DllImport("shell32.dll")] public static extern uint ExtractIconEx(string lpszFile, int nIconIndex, int[] phiconLarge, int[] phiconSmall, uint nIcons); //清空指定驅(qū)動器的回收站 [DllImport("shell32.dll")] public static extern int SHEmptyRecycleBin(IntPtr hwnd, int pszRootPath, int dwFlags); //打開系統(tǒng)的命令窗口 [DllImport("shell32.dll", EntryPoint = "ShellExecute")] public static extern int ShellExecute(int hwnd, String lpOperation, String lpFile, String lpParameters, String lpDirectory, int nShowCmd);
User32.dll
//用來釋放被當(dāng)前線程中某個窗口捕獲的光標(biāo) [DllImport("user32.dll")] public static extern bool ReleaseCapture(); //向指定的窗體發(fā)送Windows消息 [DllImport("user32.dll")] public static extern bool SendMessage(IntPtr hwdn, int wMsg, int mParam, int lParam); //獲取文件夾圖標(biāo)的API函數(shù) [DllImport("User32.dll", EntryPoint = "DestroyIcon")] public static extern int DestroyIcon(IntPtr hIcon); //查詢或設(shè)置系統(tǒng)級參數(shù) [DllImport("user32.dll", EntryPoint = "SystemParametersInfoA")] public static extern Int32 SystemParametersInfo(Int32 uAction, Int32 uParam, string lpvparam, Int32 fuwinIni); //定義系統(tǒng)API入口點,用來關(guān)閉、注銷或者重啟計算機(jī) [DllImport("user32.dll", EntryPoint = "ExitWindowsEx", CharSet = CharSet.Ansi)] public static extern int ExitWindowsEx(int uFlags, int dwReserved);
Struct數(shù)據(jù)結(jié)構(gòu)
C#中Struct數(shù)據(jù)類型此處不做更多延伸介紹,這里只說明結(jié)構(gòu)類型的語法定義規(guī)則和結(jié)構(gòu)體布局。
語法定義
//public為修飾符,People為結(jié)構(gòu)體名稱,name、age、sex為結(jié)構(gòu)體成員,每個成員包括修飾符、數(shù)據(jù)類型。 public struct People { public string name; public int age; public char sex ; };
結(jié)構(gòu)體布局
*Sequential,順序布局*
[StructLayout(LayoutKind.Sequential)] struct num { int a; int b; } //默認(rèn)情況下在內(nèi)存里是先排a,再排b //也就是如果能取到a的地址,和b的地址,則相差一個int類型的長度,4字節(jié)
*Explicit,精確布局*
*需要用FieldOffset()設(shè)置每個成員的位置
這樣就可以實現(xiàn)類似c的公用體的功能*
[StructLayout(LayoutKind.Explicit)] struct S1 { [FieldOffset(0)] int a; [FieldOffset(0)] int b; } //需要用FieldOffset()設(shè)置每個成員的位置 //這樣就可以實現(xiàn)類似c的公用體的功能
代碼案例
代碼案例中MarshalAs特性,它用于描述字段、方法或參數(shù)的封送處理格式。用它作為參數(shù)前綴并指定目標(biāo)需要的數(shù)據(jù)類型。
[StructLayout(LayoutKind.Sequential)] public struct SHFILEINFO { public IntPtr hIcon;//圖標(biāo)句柄 public IntPtr iIcon;//系統(tǒng)圖標(biāo)列表的索引 public uint dwAttributes;//文件屬性 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName;//文件的路徑 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName;//文件的類型名 }
實現(xiàn)步驟
功能類
本功能實現(xiàn)邏輯:
注銷:調(diào)用windows系統(tǒng)API函數(shù)(user32.dll)的方法。
//定義系統(tǒng)API入口點,用來關(guān)閉、注銷或者重啟計算機(jī) [DllImport("user32.dll", EntryPoint = "ExitWindowsEx", CharSet = CharSet.Ansi)] public static extern int ExitWindowsEx(int uFlags, int dwReserved)
關(guān)閉:利用Process,創(chuàng)建新進(jìn)程,打開cmd.exe,然后使用shell腳本,觸發(fā)關(guān)機(jī)動作
public void CMDOperator(string cmd) { Process myProcess = new Process();//創(chuàng)建進(jìn)程對象 myProcess.StartInfo.FileName = "cmd.exe";//設(shè)置打開cmd命令窗口 myProcess.StartInfo.UseShellExecute = false;//不使用操作系統(tǒng)shell啟動進(jìn)程的值 myProcess.StartInfo.RedirectStandardInput = true;//設(shè)置可以從標(biāo)準(zhǔn)輸入流讀取值 myProcess.StartInfo.RedirectStandardOutput = true;//設(shè)置可以向標(biāo)準(zhǔn)輸出流寫入值 myProcess.StartInfo.RedirectStandardError = true;//設(shè)置可以顯示輸入輸出流中出現(xiàn)的錯誤 myProcess.StartInfo.CreateNoWindow = true;//設(shè)置在新窗口中啟動進(jìn)程 myProcess.Start();//啟動進(jìn)程 myProcess.StandardInput.WriteLine(cmd);//傳入要執(zhí)行的命令 }
重啟:實現(xiàn)方式和關(guān)閉一樣,只不過要修改shell腳本
窗體組態(tài)
紅色邊框內(nèi)為label控件,綠色邊框內(nèi)為Button控件
事件觸發(fā)
窗體中有四個按鈕,對應(yīng)每個按鈕有四個事件,事件觸發(fā)屬性都為:click。
事件程序
//注銷按鈕事件程序 //調(diào)用win32類中的ExitWindowsEx方法。 private void button1_Click(object sender, EventArgs e) { Win32.ExitWindowsEx(0, 0);//注銷計算機(jī) } //關(guān)機(jī)按鈕事件程序 //調(diào)用Opera類中的CMDOperator方法。使用shell腳本觸發(fā) private void button2_Click(object sender, EventArgs e) { oper.CMDOperator("shutdown -s -t 0");//關(guān)閉計算機(jī) } //重啟按鈕事件程序 //調(diào)用Opera類中的CMDOperator方法。使用shell腳本觸發(fā) private void button3_Click(object sender, EventArgs e) { oper.CMDOperator("shutdown -r -t 0");//重啟計算機(jī) }
以上就是C#實現(xiàn)控制電腦注銷,關(guān)機(jī)和重啟的詳細(xì)內(nèi)容,更多關(guān)于C#控制電腦的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#操作圖片讀取和存儲SQLserver實現(xiàn)代碼
用C#將Image轉(zhuǎn)換成byte[]并插入數(shù)據(jù)庫/將圖片數(shù)據(jù)從SQLserver中取出來并顯示到pictureBox控件上,接下來將為你詳細(xì)介紹下實現(xiàn)步驟,感興趣的你可以參考下2013-03-03C#定制Excel界面并實現(xiàn)與數(shù)據(jù)庫交互的方法
這篇文章主要介紹了C#定制Excel界面并實現(xiàn)與數(shù)據(jù)庫交互的方法的相關(guān)資料,需要的朋友可以參考下2015-11-11C#使用CryptoStream類加密和解密字符串的實現(xiàn)
CryptoStream設(shè)計用于在內(nèi)容以流的形式輸出到文件時加密和解密內(nèi)容,本文主要介紹了C#使用CryptoStream類加密和解密字符串的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2024-01-01C#實現(xiàn)在Form里面內(nèi)嵌dos窗體的方法
這篇文章主要介紹了C#實現(xiàn)在Form里面內(nèi)嵌dos窗體的方法,涉及C#針對Form窗體的設(shè)置及使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-09-09