首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> 關於VC++

WMI 遠端系統管理實作:硬體資訊、服務控制、進程管理與遠端建立進程

     編輯:關於VC++

Windows Management Instrumentation (WMI) 提供統一介面查詢與管理本地/遠端系統。本文以 C# 建構四大使用者控制項(Explorer、SystemInfo、Services、Processes),示範遠端連線驗證、WQL 查詢、非同步 InvokeMethod 執行服務啟停、進程終止與建立。

核心架構

  • Explorer:Win32_LogicalDisk 列舉磁碟機。
  • SystemInfo:Win32_OperatingSystem、Win32_Processor、Win32_BIOS 等查詢硬體/OS 資訊。
  • Services:Win32_Service 列表、啟動/停止服務。
  • Processes:Win32_Process 列表、終止進程、建立新進程。

遠端連線與查詢模板

ConnectionOptions co = new ConnectionOptions();
co.Username = user; co.Password = pwd;
ManagementScope ms = new ManagementScope("\\\\" + host + "\\root\\cimv2", co);
ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_Service");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms, oq);
ManagementObjectCollection coll = searcher.Get();

非同步服務啟停與進程終止

使用 ManagementOperationObserver 監聽 ObjectReady 事件,避免 UI 凍結:

ManagementOperationObserver observer = new ManagementOperationObserver();
MyHandler handler = new MyHandler();
observer.ObjectReady += handler.Done;

foreach (ManagementObject mo in queryCollection) {
    mo.InvokeMethod(observer, "StopService", null); // 或 "Terminate"
}
// 輪詢等待完成
while (!handler.IsComplete) Thread.Sleep(500);
// 檢查 handler.ReturnObject["returnValue"] == 0 判斷成敗

遠端建立進程

ManagementClass procClass = new ManagementClass(ms, new ManagementPath("Win32_Process"), null);
object[] args = { "calc.exe", null, null, 0 }; // CommandLine, CurrentDir, StartupInfo, ProcessId(out)
procClass.InvokeMethod(observer, "Create", args);

進程擁有者查詢

// 同步呼叫取得 User/Domain
string[] outArgs = new string[2];
mo.InvokeMethod("GetOwner", outArgs); // outArgs[0]=User, [1]=Domain

// 非同步版本從 handler.ReturnObject.Properties["User"].Value 取得

狀態列更新事件

每個控制項定義 public event Status(string msg),主表單訂閱更新狀態列,提供使用者操作回饋。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved