在C#中,可以使用ManagementObjectSearcher類來執行WMI(Windows Management Instrumentation)查詢。下面是使用ManagementObjectSearcher的一般步驟:
using System.Management;
string query = "SELECT * FROM Win32_Process";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject obj in searcher.Get())
{
// 處理查詢結果
}
string processName = obj["Name"].ToString();
string processId = obj["ProcessId"].ToString();
完整示例代碼如下所示:
using System;
using System.Management;
namespace WMIExample
{
class Program
{
static void Main(string[] args)
{
string query = "SELECT * FROM Win32_Process";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject obj in searcher.Get())
{
string processName = obj["Name"].ToString();
string processId = obj["ProcessId"].ToString();
Console.WriteLine("Process Name: " + processName);
Console.WriteLine("Process ID: " + processId);
Console.WriteLine("-------------------------");
}
Console.ReadLine();
}
}
}
上述代碼將查詢并打印出所有正在運行的進程的名稱和進程ID。
請注意,ManagementObjectSearcher類還可以接受其他參數來更精確地過濾查詢結果,例如使用WHERE子句限制結果集。有關更多詳細信息,請參閱Microsoft文檔。