进程Process和服务Service是操作系统基本功能。本次查询出所有任务和所有服务(含设备驱动服务)。
一、新建Windows窗体应用程序ProcessAndServiceDemo,重命名Form1为FormProcessAndService。
窗体设计如图:
三个组合框都绑定事件SelectedIndexChanged对应的事件方法:
private void cboProcess_SelectedIndexChanged(object sender, EventArgs e)
添加对System.ServiceProcess.dll和System.Management的引用,右键项目,添加引用,如下图:
二、新建进程操作类ProcessUtil.cs。源程序如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Management;
namespace ProcessAndServiceDemo
{
/// <summary>
/// 进程相关操作
/// </summary>
public class ProcessUtil
{
/// <summary>
/// 获取所有的进程,如果进程名称一致,则只取第一次进程。
/// 因此使用HashSet来去除重复的
/// </summary>
/// <returns></returns>
public static SortedDictionary<string, Process> GetAllProcessList()
{
SortedDictionary<string, Process> dict = new SortedDictionary<string, Process>();
HashSet<string> hashSet = new HashSet<string>();
Process[] processes = Process.GetProcesses();
for (int i = 0; i < processes.Length; i++)
{
//只考虑第一个进程名
if (hashSet.Add(processes[i].ProcessName))
{
dict.Add(processes[i].ProcessName, processes[i]);
}
}
return dict;
}
/// <summary>
/// 获取进程对应的用户名
/// </summary>
/// <param name="pID"></param>
/// <returns></returns>
public static string GetProcessUserName(int pID)
{
string userName = string.Empty;
//添加对System.Management的引用
try
{
foreach (ManagementObject item in new ManagementObjectSearcher("Select * from Win32_Process WHERE processID=" + pID).Get())
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
inPar = item.GetMethodParameters("GetOwner");
outPar = item.InvokeMethod("GetOwner", inPar, null);
userName = Convert.ToString(outPar["User"]);
break;
}
}
catch
{
userName = "SYSTEM";
}
return userName;
}
/// <summary>
/// 打印当前选中的进程信息
/// </summary>
/// <param name="process"></param>
/// <returns></returns>
public static string PrintProcessMessage(Process process)
{
StringBuilder sb = new StringBuilder();
sb.Append($"进程名称:{process.ProcessName}\n");
sb.Append($"进程ID:{process.Id}\n");
sb.Append($"用户名称:{GetProcessUserName(process.Id)}\n");
try
{
sb.Append($"模块(映像)名称:{process.MainModule.ModuleName}\n");
sb.Append($"文件路径:{process.MainModule.FileName}\n");
sb.Append($"进程描述:{process.MainModule.FileVersionInfo.FileDescription}\n");
sb.Append($"启动线程数:{process.Threads.Count}\n");
sb.Append($"CPU占用时间:{process.TotalProcessorTime}\n");
sb.Append($"线程优先级:{process.PriorityClass}\n");
sb.Append($"启动时间:{process.StartTime}\n");
sb.Append($"专用内存:{process.PrivateMemorySize64 / 1024}KB\n");
sb.Append($"峰值虚拟内存:{process.PeakVirtualMemorySize64 / 1024}KB\n");
sb.Append($"峰值分页内存:{process.PagedSystemMemorySize64 / 1024}KB\n");
sb.Append($"分页系统内存:{process.PagedMemorySize64 / 1024}KB\n");
sb.Append($"分页内存:{process.PagedMemorySize64 / 1024}KB\n");
sb.Append($"未分页系统内存:{process.NonpagedSystemMemorySize64 / 1024}KB\n");
sb.Append($"物理内存:{process.WorkingSet64 / 1024}KB\n");
sb.Append($"虚拟内存:{process.VirtualMemorySize64 / 1024}KB");
}
catch (Exception ex)
{
sb.Append($"访问或操作失败:{ex.Message}\n");
}
return sb.ToString();
}
}
}
三、新建服务操作类ServiceUtil.cs。源程序如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.ServiceProcess;
using Microsoft.Win32;
namespace ProcessAndServiceDemo
{
/// <summary>
/// 服务相关操作:
/// 服务分一般服务、设备驱动程序服务(硬件服务)
/// </summary>
public class ServiceUtil
{
/// <summary>
/// 获取所有设备驱动程序服务
/// </summary>
/// <returns></returns>
public static SortedDictionary<string, ServiceController> GetAllDeviceServiceList()
{
SortedDictionary<string, ServiceController> dict = new SortedDictionary<string, ServiceController>();
ServiceController[] allDevices = ServiceController.GetDevices();
for (int i = 0; i < allDevices.Length; i++)
{
dict.Add(allDevices[i].ServiceName, allDevices[i]);
}
return dict;
}
/// <summary>
/// 获取所有的一般服务
/// </summary>
/// <returns></returns>
public static SortedDictionary<string, ServiceController> GetAllNormalServiceList()
{
SortedDictionary<string, ServiceController> dict = new SortedDictionary<string, ServiceController>();
ServiceController[] allService = ServiceController.GetServices();
for (int i = 0; i < allService.Length; i++)
{
dict.Add(allService[i].ServiceName, allService[i]);
}
return dict;
}
/// <summary>
/// 打印当前选中的服务信息
/// </summary>
/// <param name="service"></param>
/// <returns></returns>
public static string PrintServiceMessage(ServiceController service)
{
StringBuilder sb = new StringBuilder();
sb.Append($"服务名称:{service.ServiceName}\n");
sb.Append($"标识名称(描述):{service.DisplayName}\n");
sb.Append($"服务状态:{service.Status}\n");
sb.Append($"服务类型:{service.ServiceType}\n");
sb.Append($"服务状态:{service.Status}\n");
sb.Append($"是否可以停止服务:{service.CanStop}\n");
sb.Append($"是否可以暂停和继续服务:{service.CanPauseAndContinue}\n");
/*
类ServiceController不提供系统服务的路径与描述信息,需要通过访问注册表来实现。
注册表SYSTEM\\CurrentControlSet\\services\\下,存放与系统服务名称一一对应的系统服务信息,
取ImagePath键值可获得系统服务路径;
取Description键值可获得系统服务描述信息。
*/
try
{
//从注册表中取路径
RegistryKey regKey = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\services\\" + service.ServiceName);
sb.Append($"服务路径:{regKey.GetValue("ImagePath")}\n");
sb.Append($"服务描述(额外):{regKey.GetValue("Description")}\n");
ServiceController[] dependedOnServices = service.ServicesDependedOn;
List<string> dependedOnServiceNames = new List<string>();
dependedOnServices.ToList().ForEach(svc => dependedOnServiceNames.Add(svc.ServiceName));
sb.Append($"所依赖的服务:【{string.Join(",", dependedOnServiceNames)}】\n");
ServiceController[] relatedServices = service.DependentServices;
List<string> relatedServiceNames = new List<string>();
relatedServices.ToList().ForEach(svc => relatedServiceNames.Add(svc.ServiceName));
sb.Append($"相关联的服务:【{string.Join(",", relatedServiceNames)}】");
}
catch (Exception ex)
{
sb.Append($"访问或操作失败:{ex.Message}\n");
}
return sb.ToString();
}
}
}
四、窗体显示类FormProcessAndService.cs。源程序如下:(忽略设计器自动生成的代码)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProcessAndServiceDemo
{
public partial class FormProcessAndService : Form
{
/// <summary>
/// 是否已加载绑定列表完成
/// </summary>
bool isLoad = false;
public FormProcessAndService()
{
InitializeComponent();
}
private void FormProcessAndService_Load(object sender, EventArgs e)
{
//绑定【进程】列表
SortedDictionary<string, Process> dictProcess = ProcessUtil.GetAllProcessList();
BindComboBoxData(cboProcess, dictProcess);
//绑定【设备驱动程序服务】列表
SortedDictionary<string, ServiceController> dictDeviceService = ServiceUtil.GetAllDeviceServiceList();
BindComboBoxData(cboDeviceService, dictDeviceService);
//绑定【一般服务】列表
SortedDictionary<string, ServiceController> dictNormalService = ServiceUtil.GetAllNormalServiceList();
BindComboBoxData(cboNormalService, dictNormalService);
isLoad = true;
cboProcess_SelectedIndexChanged(cboProcess, e);
cboProcess_SelectedIndexChanged(cboDeviceService, e);
cboProcess_SelectedIndexChanged(cboNormalService, e);
}
/// <summary>
/// 为组合框绑定数据源,使用【排序字典】。键为string名称,值为【进程或服务对象】
/// </summary>
/// <param name="cbo"></param>
/// <param name="dataSource"></param>
private void BindComboBoxData(ComboBox cbo, object dataSource)
{
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = dataSource;
cbo.DataSource = bindingSource;
cbo.ValueMember = "Value";
cbo.DisplayMember = "Key";
if (cbo.Items.Count > 0)
{
cbo.SelectedIndex = 0;
}
}
/// <summary>
/// 组合框选择的索引改变事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cboProcess_SelectedIndexChanged(object sender, EventArgs e)
{
if (!isLoad)
{
return;
}
ComboBox cbo = sender as ComboBox;
if (cbo == null || cbo.SelectedIndex < 0)
{
return;
}
try
{
switch (cbo.Name)
{
case "cboProcess":
//【进程】信息显示
Process process = cbo.SelectedValue as Process;
string messageProcess = ProcessUtil.PrintProcessMessage(process);
DisplayMessage(messageProcess, rtxtProcess);
break;
case "cboDeviceService":
//【设备驱动程序服务】信息显示
ServiceController deviceService = cbo.SelectedValue as ServiceController;
string messageDevice = ServiceUtil.PrintServiceMessage(deviceService);
DisplayMessage(messageDevice, rtxtDeviceService);
break;
case "cboNormalService":
//【一般服务】信息显示
ServiceController normalService = cbo.SelectedValue as ServiceController;
string messageService = ServiceUtil.PrintServiceMessage(normalService);
DisplayMessage(messageService, rtxtNormalService);
break;
}
}
catch (Exception ex)
{
DisplayMessage($"出现未知异常:{ex.Message}", rtxtProcess);
}
}
/// <summary>
/// 显示进程或服务的详细内容
/// </summary>
/// <param name="message"></param>
/// <param name="rtxtDisplay"></param>
public void DisplayMessage(string message, RichTextBox rtxtDisplay)
{
try
{
this.BeginInvoke(new Action(() =>
{
rtxtDisplay.Clear();
rtxtDisplay.AppendText($"{message}\n");
rtxtDisplay.ScrollToCaret();
}));
}
catch (Exception ex)
{
MessageBox.Show("显示消息时出现异常:" + ex.Message, "出现异常");
}
}
}
}
五、程序运行如图: