日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#實現控制電腦注銷,關機和重啟_C#教程

作者:yue008 ? 更新時間: 2022-11-11 編程語言

實現目標

通過C#實現電腦的注銷、關機、重啟功能

知識點

本案例涉及的知識點包含:Process、Shell32.dll、User32.dll、Struct數據結構。

Process

本案例主要通過Process類調用cmd.exe.使用shell命令實現電機的關機和重啟。

用到的屬性和方法有:StartInfo(屬性) 和Start(方法)。

StartInfo.FileName

獲取或設置要啟動的應用程序或文檔。

Process.StartInfo.FileName 
Process.StartInfo.FileName = "cmd.exe"

StartInfo.UseShellExecute

如果應在啟動進程時使用 shell,則為 true;如果直接從可執行文件創建進程,則為 false。 默認值為true。

以下場景值為True:

需要打開文檔、媒體、網頁文件等 需要打開 Url 需要打開腳本執行 需要打開計算機上環境變量中路徑中的程序

以下場景值為False:

需要明確執行一個已知的程序 需要重定向輸入和輸出

UseShellExecute = true 調用的是 ShellExecute

UseShellExecute = false 調用的是 CreateProcess

Process.StartInfo.UseShellExecute 
Process.StartInfo.UseShellExecute = false

StartInfo.RedirectStandardInput

獲取用于寫入應用程序輸入的流。

如果應從 StandardInput 讀取輸入,則為 true;否則為 false。 默認值為 false。

A Process 可以從其標準輸入流(通常是鍵盤)讀取輸入文本。 通過重定向 StandardInput 流,可以編程方式指定進程的輸入。 例如,你可以從指定文件的內容或從另一個應用程序的輸出中提供文本,而不是使用鍵盤輸入。

StartInfo.RedirectStandardOutput

獲取或設置指示是否將應用程序的文本輸出寫入 StandardOutput 流中的值。

如果輸出應寫入 StandardOutput,則為 true;否則為 false。 默認值為 false。

Process當將文本寫入其標準流時,該文本通常顯示在主機上。 通過設置為RedirectStandardOutputtrue重定向StandardOutput流,可以操作或取消進程的輸出。 例如,可以篩選文本、以不同的方式設置格式,或將輸出寫入控制臺和指定的日志文件。

// 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

獲取或設置指示是否將應用程序的錯誤輸出寫入 StandardError 流中的值。

如果錯誤輸出應寫入 StandardError,則為 true;否則為 false。 默認值為 false。

Process當將文本寫入其標準錯誤流時,該文本通常顯示在主機上。 通過重定向 StandardError 流,可以操作或禁止進程的錯誤輸出。 例如,可以篩選文本、以不同的方式設置格式,或將輸出寫入控制臺和指定的日志文件.

StartInfo.CreateNoWindow

獲取或設置指示是否在新窗口中啟動該進程的值。

如果應啟動進程而不創建包含它的新窗口,則為true ;否則為 false。 默認值為 false。

對控制面板窗口有效,與 UseShellExecute 結合使用。

UseShellExecute = true 時此值無效,為正常方式啟動。

UseShellExecute = false;CreateNoWindow = true 時,控制面板窗口不會顯示。這種方式下無法通過窗口關閉進程,所以運行的進程最好是可以自己運行完關閉的,不然需要到任務管理器中關閉。

Start

啟動進程資源并將其與 Process 組件關聯。

StandardInput.WriteLine(cmd)

獲取用于寫入應用程序輸入的流。

StreamWriter,可用于寫入應用程序的標準輸入流。

shell32.dll

public static extern bool SendMessage(IntPtr hwdn, int wMsg, int mParam, int lParam);
//從exe\dll\ico文件中獲取指定索引或ID號的圖標句柄
[DllImport("shell32.dll", EntryPoint = "ExtractIcon")]

//獲取文件圖標的API函數
[DllImport("shell32.dll", EntryPoint = "SHGetFileInfo")]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttribute, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint Flags);

//從exe\dll\ico文件中生成圖標句柄數組
[DllImport("shell32.dll")]
public static extern uint ExtractIconEx(string lpszFile, int nIconIndex, int[] phiconLarge, int[] phiconSmall, uint nIcons);

//清空指定驅動器的回收站
[DllImport("shell32.dll")]
public static extern int SHEmptyRecycleBin(IntPtr hwnd, int pszRootPath, int dwFlags);

//打開系統的命令窗口
[DllImport("shell32.dll", EntryPoint = "ShellExecute")]
public static extern int ShellExecute(int hwnd, String lpOperation, String lpFile, String lpParameters, String lpDirectory, int nShowCmd);

User32.dll

  //用來釋放被當前線程中某個窗口捕獲的光標
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        //向指定的窗體發送Windows消息
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwdn, int wMsg, int mParam, int lParam);
        //獲取文件夾圖標的API函數
        [DllImport("User32.dll", EntryPoint = "DestroyIcon")]
        public static extern int DestroyIcon(IntPtr hIcon);
        //查詢或設置系統級參數
        [DllImport("user32.dll", EntryPoint = "SystemParametersInfoA")]
        public static extern Int32 SystemParametersInfo(Int32 uAction, Int32 uParam, string lpvparam, Int32 fuwinIni);
        //定義系統API入口點,用來關閉、注銷或者重啟計算機
        [DllImport("user32.dll", EntryPoint = "ExitWindowsEx", CharSet = CharSet.Ansi)]
        public static extern int ExitWindowsEx(int uFlags, int dwReserved);

Struct數據結構

C#中Struct數據類型此處不做更多延伸介紹,這里只說明結構類型的語法定義規則和結構體布局。

語法定義

//public為修飾符,People為結構體名稱,name、age、sex為結構體成員,每個成員包括修飾符、數據類型。
public struct People
{
   public string name;
   public int age;
   public char sex ;
};  

結構體布局

*Sequential,順序布局*

[StructLayout(LayoutKind.Sequential)]
struct num
{
    int a;
    int b;
}
//默認情況下在內存里是先排a,再排b
//也就是如果能取到a的地址,和b的地址,則相差一個int類型的長度,4字節

*Explicit,精確布局*

*需要用FieldOffset()設置每個成員的位置

這樣就可以實現類似c的公用體的功能*

[StructLayout(LayoutKind.Explicit)]
struct S1
{
  [FieldOffset(0)]
  int a;
  [FieldOffset(0)]
  int b;
}
//需要用FieldOffset()設置每個成員的位置
//這樣就可以實現類似c的公用體的功能

代碼案例

代碼案例中MarshalAs特性,它用于描述字段、方法或參數的封送處理格式。用它作為參數前綴并指定目標需要的數據類型。

[StructLayout(LayoutKind.Sequential)]
 public struct SHFILEINFO
 {
     public IntPtr hIcon;//圖標句柄
     public IntPtr iIcon;//系統圖標列表的索引
     public uint dwAttributes;//文件屬性
     [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
     public string szDisplayName;//文件的路徑
     [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
     public string szTypeName;//文件的類型名
 }

實現步驟

功能類

本功能實現邏輯:

注銷:調用windows系統API函數(user32.dll)的方法。

//定義系統API入口點,用來關閉、注銷或者重啟計算機
[DllImport("user32.dll", EntryPoint = "ExitWindowsEx", CharSet = CharSet.Ansi)]
public static extern int ExitWindowsEx(int uFlags, int dwReserved)

關閉:利用Process,創建新進程,打開cmd.exe,然后使用shell腳本,觸發關機動作

 public void CMDOperator(string cmd)
 {
     Process myProcess = new Process();//創建進程對象
     myProcess.StartInfo.FileName = "cmd.exe";//設置打開cmd命令窗口
     myProcess.StartInfo.UseShellExecute = false;//不使用操作系統shell啟動進程的值
     myProcess.StartInfo.RedirectStandardInput = true;//設置可以從標準輸入流讀取值
     myProcess.StartInfo.RedirectStandardOutput = true;//設置可以向標準輸出流寫入值
     myProcess.StartInfo.RedirectStandardError = true;//設置可以顯示輸入輸出流中出現的錯誤
     myProcess.StartInfo.CreateNoWindow = true;//設置在新窗口中啟動進程
     myProcess.Start();//啟動進程
     myProcess.StandardInput.WriteLine(cmd);//傳入要執行的命令
}

重啟:實現方式和關閉一樣,只不過要修改shell腳本

窗體組態

紅色邊框內為label控件,綠色邊框內為Button控件

事件觸發

窗體中有四個按鈕,對應每個按鈕有四個事件,事件觸發屬性都為:click。

事件程序

//注銷按鈕事件程序
//調用win32類中的ExitWindowsEx方法。
 private void button1_Click(object sender, EventArgs e)
{
    Win32.ExitWindowsEx(0, 0);//注銷計算機
}
//關機按鈕事件程序
//調用Opera類中的CMDOperator方法。使用shell腳本觸發
 private void button2_Click(object sender, EventArgs e)
 {
     oper.CMDOperator("shutdown -s -t 0");//關閉計算機
 }
//重啟按鈕事件程序
//調用Opera類中的CMDOperator方法。使用shell腳本觸發
private void button3_Click(object sender, EventArgs e)
{
    oper.CMDOperator("shutdown -r -t 0");//重啟計算機
}

原文鏈接:https://blog.csdn.net/yue008/article/details/126950792

欄目分類
最近更新