在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文档。