C#实现获取远程计算机上所有的进程(附完整源代码)

时间:2025-04-01 08:31:34
using System; using System.Management; // 引入命名空间namespace RemoteProcessViewer { class Program { static void Main(string[] args) { Console.WriteLine("请输入远程计算机的名称或IP地址:"); string remoteMachineName = Console.ReadLine();// 确保输入了远程计算机的名称 if (string.IsNullOrWhiteSpace(remoteMachineName)) { Console.WriteLine("远程计算机名称不能为空!"); return; }try { // 设置WMI连接选项 ConnectionOptions options = new ConnectionOptions(); // 在此处设置远程计算机的用户名和密码,如果需要的话 // = "yourUsername"; // = "yourPassword";ManagementScope scope = new ManagementScope($"\\\\{remoteMachineName}\\root\\cimv2", options); scope.Connect(); // 尝试连接到远程计算机// 查询远程计算机上的所有进程 ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Process"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);foreach (ManagementObject queryObj in searcher.Get()) { Console.WriteLine($"Process ID: {queryObj["ProcessId"]}, Process Name: {queryObj["Name"]}"); } } catch (Exception e) { Console.WriteLine($"发生错误: {e.Message}"); } ​ Console.WriteLine("按任意键退出..."); Console.ReadKey(); } } }