吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1213|回复: 5
上一主题 下一主题
收起左侧

开源一款轻量化ProcessMonitor 进程管理工具

[复制链接]
跳转到指定楼层
楼主
summer581 发表于 2026-7-31 22:47 回帖奖励
本帖最后由 summer581 于 2026-7-31 22:50 编辑

0x00 项目概览

ProcessMonitor 是一个基于 WPF + .NET 9 的 Windows 进程观察工具,当前形态已经接近一个轻量版 Process Hacker:

  • 支持进程树展示
  • 支持自动刷新
  • 支持搜索过滤
  • 支持进程终止与进程树终止
  • 支持线程列表
  • 支持注册表关联扫描
  • 支持图标、颜色、描述、用户名等辅助信息

它的设计思路不是做成“纯列表监控器”,而是做成一个可继续扩展的进程控制台。界面上以进程树为主,下方保留详情区域,布局和交互都向 Process Hacker 靠拢。


0x01 工程结构

项目结构非常直接,核心分三层:

src/ProcessMonitor.App/
├── MainWindow.xaml
├── MainWindow.xaml.cs
├── App.xaml
├── App.xaml.cs
├── Models/
│   ├── ProcessSnapshot.cs
│   ├── ProcessTreeNode.cs
│   ├── ProcessTreeRow.cs
│   ├── RegistryAssociation.cs
│   ├── SystemSnapshot.cs
│   └── ThreadSnapshot.cs
├── Services/
│   ├── ProcessSnapshotService.cs
│   ├── ProcessIconService.cs
│   └── RegistryAssociationService.cs
└── ProcessMonitor.App.csproj

对应关系很清楚:

  • Models 负责数据结构
  • Services 负责和系统交互
  • MainWindow.xaml 负责界面
  • MainWindow.xaml.cs 负责交互、刷新、选择、详情联动

项目文件也很简单:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net9.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UseWPF>true</UseWPF>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="System.Management" Version="10.0.10" />
  </ItemGroup>
</Project>

这里唯一的显式包是 System.Management,用来读 WMI 的 Win32_Process / Win32_Service。


0x02 架构总线

整个项目的运行链路可以概括为:

UI(MMainWindow)
  -> ProcessSnapshotService.GetSnapshot()
      -> Process.GetProcesses()
      -> WMI Win32_Process / Win32_Service
      -> Win32 API / Shell API
  -> BuildProcessTree()
  -> ObservableCollection<ProcessTreeRow>
  -> DataGrid

0x03 快照采集层

快照采集是这个项目的骨架。当前实现不是只靠 WMI,而是把多个来源拼在一起:

  • Process.GetProcesses():保证枚举有底
  • Win32_Process:补父 PID、命令行、创建时间、线程数、句柄数、工作集等
  • Win32_Service:补服务进程归属
  • OpenProcess / QueryFullProcessImageName:拿路径
  • OpenProcessToken / WindowsIdentity:拿用户名
  • GetProcessIoCounters:算 I/O 速率
  • GetSystemTimes / GlobalMemoryStatusEx:算 CPU 和内存概况

这部分的核心代码在 ProcessSnapshotService.GetSnapshot():

public SystemSnapshot GetSnapshot()
{
    var capturedAt = DateTimeOffset.Now;
    var wmiProcesses = ReadWmiProcesses();
    var serviceProcesses = ReadServiceProcesses();
    var activeIdentities = new HashSet<ProcessIdentity>();
    var processes = new List<ProcessSnapshot>();
    var seenProcessIds = new HashSet<int>();
    var elapsed = _previousCaptureTime is null ? TimeSpan.Zero : capturedAt - _previousCaptureTime.Value;

    foreach (var process in Process.GetProcesses())
    {
        using (process)
        {
            var processId = process.Id;
            if (!seenProcessIds.Add(processId))
            {
                continue;
            }

            wmiProcesses.TryGetValue(processId, out var wmi);
            var startTime = wmi?.StartTime ?? SafeRead<DateTimeOffset?>(() => new DateTimeOffset(process.StartTime), null);
            var identity = new ProcessIdentity(processId, startTime?.UtcTicks ?? 0);
            activeIdentities.Add(identity);

            var executablePath = wmi?.ExecutablePath;
            if (string.IsNullOrWhiteSpace(executablePath))
            {
                executablePath = TryGetProcessPath(processId);
            }

            var totalProcessorTime = wmi?.TotalProcessorTime ?? SafeRead(() => process.TotalProcessorTime, TimeSpan.Zero);
            var ioTotalBytes = wmi?.IoTotalBytes ?? TryGetIoTotalBytes(processId);
            var counters = CalculateCounters(identity, totalProcessorTime, ioTotalBytes, elapsed);
            ...
        }
    }

    return new SystemSnapshot(
        processes.OrderBy(process => process.ProcessId).ToList(),
        ReadSystemCpuUsage(),
        memory.UsedBytes,
        memory.TotalBytes,
        capturedAt);
}

这段里最值得注意的是两个点:

  1. 单个进程失败不会拖垮整个快照
  2. CPU / I/O 是基于前后两次快照的增量,不是拍脑袋写死的值

WMI 和本机进程对象都会遇到权限问题,所以每个字段都做了单独兜底。

ProcessSnapshot 把这些原始信息再包装成 UI 好用的字段:

public sealed class ProcessSnapshot
{
    public required string Name { get; init; }
    public required int ProcessId { get; init; }
    public int ParentProcessId { get; init; }
    public string? ExecutablePath { get; init; }
    public string? CommandLine { get; init; }
    public DateTimeOffset? StartTime { get; init; }
    public int ThreadCount { get; init; }
    public int HandleCount { get; init; }
    public long WorkingSetBytes { get; init; }
    public long PrivateBytes { get; init; }
    public double CpuUsagePercent { get; init; }
    public double IoTotalRateBytes { get; init; }
    public string? UserName { get; init; }
    public string? Description { get; init; }
    public int SessionId { get; init; }
    public bool IsService { get; init; }
    public bool IsCurrentUser { get; init; }
    public bool IsWindowsProcess { get; init; }
    public bool IsPackagedProcess { get; init; }
}

0x04 进程树构建

Process Hacker 风格的关键,不是“列出进程”,而是“把进程摆成树”。

当前树构建逻辑在 BuildProcessTree() 和 CanAttachToParent() 里:

public IReadOnlyList<ProcessTreeNode> BuildProcessTree(IReadOnlyList<ProcessSnapshot> processes)
{
    var nodes = processes
        .GroupBy(process => process.ProcessId)
        .Select(group => group.First())
        .ToDictionary(process => process.ProcessId, process => new ProcessTreeNode(process));
    var roots = new List<ProcessTreeNode>();

    foreach (var process in processes.GroupBy(process => process.ProcessId).Select(group => group.First()))
    {
        var node = nodes[process.ProcessId];
        if (CanAttachToParent(process, nodes, out var parent))
        {
            parent.Children.Add(node);
        }
        else
        {
            roots.Add(node);
        }
    }

    foreach (var root in roots)
    {
        SortTree(root);
    }

    return roots.OrderBy(node => GetTreeSortKey(node.Process)).ThenBy(node => node.Process.ProcessId).ToList();
}

父子关系并不是“只要 ParentProcessId 对上就硬挂”,还会校验:

  • 父 PID 不能等于自己
  • 父 PID 不能是 0 或无效值
  • 父节点必须真实存在
  • 父进程创建时间不能晚于子进程
  • 祖先链里如果出现循环,直接断开

这段是关键:

private static bool CanAttachToParent(
    ProcessSnapshot process,
    IReadOnlyDictionary<int, ProcessTreeNode> nodes,
    out ProcessTreeNode parent)
{
    parent = null!;
    if (process.ProcessId <= 4 ||
        process.ParentProcessId <= 0 ||
        process.ParentProcessId == process.ProcessId ||
        !nodes.TryGetValue(process.ParentProcessId, out var resolvedParent))
    {
        return false;
    }

    parent = resolvedParent;
    if (process.StartTime is not null &&
        parent.Process.StartTime is not null &&
        parent.Process.StartTime > process.StartTime)
    {
        return false;
    }

    var visited = new HashSet<int> { process.ProcessId };
    var ancestor = parent.Process;
    while (ancestor.ParentProcessId > 0 &&
           ancestor.ParentProcessId != ancestor.ProcessId &&
           nodes.TryGetValue(ancestor.ParentProcessId, out var next))
    {
        if (ancestor.StartTime is not null &&
            next.Process.StartTime is not null &&
            next.Process.StartTime > ancestor.StartTime)
        {
            break;
        }

        if (!visited.Add(next.Process.ProcessId))
        {
            return false;
        }

        ancestor = next.Process;
    }

    return true;
}

这保证了树不是“错挂一气”,而是尽可能接近真实进程父子结构。


0x05 主界面布局

界面由四部分组成:

  • 顶部菜单
  • 工具栏
  • 中间 Processes 主表
  • 底部状态栏和下方面板

当前界面是 code-behind 驱动,没有引入独立 MVVM 框架,这样做的好处是:

  • 逻辑链短
  • 调试方便
  • 交互能快速改
  • 对这个体量的工具足够直接
<DataGrid Grid.Row="0"
          x:Name="ProcessGrid"
          AutomationProperties.Name="Processes"
          FrozenColumnCount="1"
          RowStyle="{StaticResource ProcessRowStyle}"
          SelectionChanged="ProcessGrid_SelectionChanged"
          MouseDoubleClick="ProcessGrid_MouseDoubleClick">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Name" Width="275">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="16" />
                            <ColumnDefinition Width="21" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>
                        <Border Width="{Binding IndentWidth}" />
                        <Button Grid.Column="1"
                                Style="{StaticResource TreeToggleButton}"
                                Visibility="{Binding ToggleVisibility}"
                                Click="TreeToggleButton_Click">
                            <Path ... />
                        </Button>
                        <Image Grid.Column="2"
                               Source="{Binding Icon}"
                               Width="16"
                               Height="16" />
                        <TextBlock Grid.Column="3"
                                   Text="{Binding Process.Name}" />
                    </Grid>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Header="PID" Binding="{Binding Process.ProcessId}" Width="62" />
        <DataGridTextColumn Header="CPU" Binding="{Binding Process.CpuUsageText}" Width="58" />
        <DataGridTextColumn Header="I/O total rate" Binding="{Binding Process.IoTotalRateText}" Width="102" />
        <DataGridTextColumn Header="Private bytes" Binding="{Binding Process.PrivateBytesText}" Width="98" />
        <DataGridTextColumn Header="User name" Binding="{Binding Process.UserName}" Width="180" />
        <DataGridTextColumn Header="Description" Binding="{Binding Process.Description}" Width="*" MinWidth="190" />
    </DataGrid.Columns>
</DataGrid>
<Button x:Name="RefreshButton" ... />
<Button x:Name="OptionsButton" ... />
<Button x:Name="FindButton" ... />
<Button x:Name="SystemInformationButton" ... />
<ToggleButton x:Name="AutoRefreshButton" ... />
<Button x:Name="ExpandAllButton" ... />
<Button x:Name="CollapseAllButton" ... />
<Button x:Name="PropertiesButton" ... />
<Button x:Name="TerminateButton" ... />

0x06 颜色、图标与行样式

进程树的视觉信息不是装饰,而是降低扫描成本的关键。

当前 ProcessTreeRow 按进程属性决定行背景:

public Brush RowBackground
{
    get
    {
        if (Process.ProcessId == Environment.ProcessId)
        {
            return CurrentProcessBrush;
        }

        if (Process.ProcessId <= 4)
        {
            return CoreSystemBrush;
        }

        if (Process.IsService)
        {
            return ServiceBrush;
        }

        if (Process.IsPackagedProcess)
        {
            return PackagedBrush;
        }

        if (Process.IsCurrentUser)
        {
            return CurrentUserBrush;
        }

        if (Process.IsWindowsProcess)
        {
            return WindowsProcessBrush;
        }

        return Brushes.White;
    }
}

图标则由 ProcessIconService 从系统 shell 图标提取并缓存:

public ImageSource? GetIcon(ProcessSnapshot process)
{
    var path = process.ExecutablePath;
    if (!string.IsNullOrWhiteSpace(path) && File.Exists(path))
    {
        return _cache.GetOrAdd(path, static value => ExtractIcon(value, useFileAttributes: false));
    }

    return _cache.GetOrAdd(
        GenericExecutableCacheKey,
        static _ => ExtractIcon("process.exe", useFileAttributes: true));
}

这意味着:

  • 已知路径的进程会显示真实图标
  • 不可访问路径会退回通用可执行图标
  • 图标结果有缓存,不会每次刷新都重新抽取

0x07 详情面板与辅助信息

选中一条进程后,界面会同步更新:

  • General:文本详情
  • Threads:线程列表
  • Registry:注册表关联

主要入口在 SelectProcessAsync():

private async Task SelectProcessAsync(ProcessSnapshot process)
{
    var selectionVersion = ++_selectionVersion;
    _selectedProcess = process;
    UpdateProcessCommandState(process);
    DetailsText.Text = BuildDetailsText(process);
    StatusText.Text = $"Selected {process.Name} ({process.ProcessId})";

    ThreadGrid.ItemsSource = null;
    RegistryGrid.ItemsSource = null;

    var threadsTask = Task.Run(() => _processService.GetThreads(process.ProcessId));
    var registryTask = Task.Run(() => _registryService.FindAssociations(process));
    var threads = await threadsTask;
    var registry = await registryTask;

    if (selectionVersion != _selectionVersion ||
        _selectedProcess?.ProcessId != process.ProcessId)
    {
        return;
    }

    ThreadGrid.ItemsSource = threads;
    RegistryGrid.ItemsSource = registry;
}

General 面板的内容是拼出来的,便于直接复制、讲解、排查:

private string BuildDetailsText(ProcessSnapshot process)
{
    var parent = _lastSnapshot.FirstOrDefault(item => item.ProcessId == process.ParentProcessId);
    var builder = new StringBuilder();
    builder.AppendLine($"Name:           {process.Name}");
    builder.AppendLine($"Description:    {process.Description ?? "(unavailable)"}");
    builder.AppendLine($"PID:            {process.ProcessId}");
    builder.AppendLine($"Parent PID:     {process.ParentProcessId}");
    builder.AppendLine($"Parent:         {(parent is null ? "(not in current snapshot)" : $"{parent.Name} ({parent.ProcessId})")}");
    builder.AppendLine($"User:           {process.UserName ?? "(unavailable)"}");
    builder.AppendLine($"Session:        {process.SessionId}");
    builder.AppendLine($"Path:           {process.ExecutablePath ?? "(unavailable)"}");
    builder.AppendLine($"Command line:   {process.CommandLine ?? "(unavailable)"}");
    builder.AppendLine($"Started:        {process.StartTimeText}");
    builder.AppendLine($"CPU:            {(process.CpuUsagePercent <= 0.004 ? "0" : process.CpuUsagePercent.ToString("0.##"))}%");
    builder.AppendLine($"I/O total rate: {(process.IoTotalRateBytes <= 0.5 ? "0 B/s" : process.IoTotalRateText)}");
    builder.AppendLine($"Private bytes:  {process.PrivateBytesText}");
    builder.AppendLine($"Working set:    {process.WorkingSetText}");
    builder.AppendLine($"Threads:        {process.ThreadCount}");
    builder.AppendLine($"Handles:        {process.HandleCount}");
    return builder.ToString();
}

注册表关联扫描当前不是全系统实时跟踪,而是“围绕目标进程名和路径做定位扫描”。这已经能覆盖非常多实际排查场景:

public IReadOnlyList<RegistryAssociation> FindAssociations(ProcessSnapshot process)
{
    var results = new List<RegistryAssociation>();
    ScanHive(results, RegistryHive.CurrentUser, RegistryView.Default, process);
    ScanHive(results, RegistryHive.LocalMachine, RegistryView.Registry64, process);
    ScanHive(results, RegistryHive.LocalMachine, RegistryView.Registry32, process);
    return results
        .DistinctBy(item => $"{item.Hive}|{item.View}|{item.KeyPath}|{item.ValueName}|{item.Data}", StringComparer.OrdinalIgnoreCase)
        .OrderBy(item => item.Kind, StringComparer.OrdinalIgnoreCase)
        .ThenBy(item => item.KeyPath, StringComparer.OrdinalIgnoreCase)
        .ToList();
}


0x08 自动刷新与滚动稳定性

这个项目里最容易“烦人”的交互点就是自动刷新后视图跳回顶部。当前版本已经处理了这个问题:

  1. 自动刷新前捕获 ScrollViewer 的纵向和横向偏移
  2. 重建列表
  3. 仅在手动刷新或显式选择时滚动到选中项
  4. 自动刷新结束后恢复原滚动位置

对应代码如下:

private async Task RefreshSnapshotAsync(bool isAutomatic = false)
{
    if (_isRefreshing)
    {
        return;
    }

    try
    {
        _isRefreshing = true;
        if (!isAutomatic)
        {
            SetBusy(true, "Refreshing process snapshot...");
        }

        var selectedPid = _selectedProcess?.ProcessId;
        var viewport = isAutomatic ? CaptureProcessGridViewport() : null;
        var snapshot = await Task.Run(_processService.GetSnapshot);
        _lastSnapshot = snapshot.Processes;
        _processTreeRoots = _processService.BuildProcessTree(_lastSnapshot);
        RemoveStaleCollapseState();
        PopulateProcessRows();
        RestoreGridSelection(selectedPid, scrollIntoView: !isAutomatic);
        ...
        if (isAutomatic)
        {
            await RestoreProcessGridViewportAsync(viewport);
        }
    }
    finally
    {
        ...
        _isRefreshing = false;
    }
}

这部分的经验很实用:

  • 自动刷新应该保留用户当前阅读位置
  • 手动刷新可以更积极地回到选中项
  • 搜索过滤则应该显式重建筛选结果,但不要乱改视图状态

">

0x09 可访问性与操作一致性

当前界面已经补了基础的可访问性名称,避免工具按钮只有图标没名字:

<Button x:Name="RefreshButton" AutomationProperties.Name="Refresh" ... />
<Button x:Name="OptionsButton" AutomationProperties.Name="Options" ... />
<Button x:Name="FindButton" AutomationProperties.Name="Find handles or DLLs" ... />
<Button x:Name="SystemInformationButton" AutomationProperties.Name="System information" ... />
<ToggleButton x:Name="AutoRefreshButton" AutomationProperties.Name="Auto refresh" ... />
<DataGrid x:Name="ProcessGrid" AutomationProperties.Name="Processes" ... />

这类细节看起来不大,但会直接影响:

  • 屏幕阅读器可用性
  • 自动化测试稳定性
  • 后续做 UI 交互验证时的定位精度

0x0A 当前能力边界

现在这个版本已经能用,但它还不完善。当前边界主要有这些:

  • CPU 和 I/O 是“基于两次快照差值”的估算值,不是 ETW 级别实时统计
  • 某些受保护进程的路径、用户名、句柄信息可能拿不到
  • 注册表关联扫描是启发式的,不是实时注册表审计
  • Services / Network / Disk 目前还是占位页
  • 右键菜单和工具栏已经有骨架,但还可以继续补全更完整的操作集

0x0B 构建与运行

构建命令:

dotnet build ProcessMonitor.sln

发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

推荐
kagayaki 发表于 2026-8-17 05:20
本帖最后由 kagayaki 于 2026-9-26 09:22 编辑

感谢开源,十多年前,当时要做一个监时进程运行和退出的功能,这个功能我也用 WMI, 后来才发现,WMI 的功能,在大部份电脑上不能正常执行,原因很多,后来就打死都不用WMI了,查进程调用 NtQuerySystemInformation(SystemProcessInformation),用户层最快,不存在权限问题,通用所有系统。
用户层大部份的API,最终还是调用 Nt** API, 比如:

GetCurrentProcess      是   NtCurrentProcess
GetCurrentProcessId    是   NtCurrentTeb()->ClientId.UniqueProcess
GetProcessId           是   NtQueryInformationProcess
OpenProcess            是   NtOpenProcess
TerminateProcess       是   NtTerminateProcess
GetProcessTimes        是   NtQueryInformationProcess
ReadProcessMemory      是   NtReadVirtualMemory
WriteProcessMemory     是   NtProtectVirtualMemory 和 NtWriteVirtualMemory 和 NtFlushInstructionCache
GetSystemInfo          是   NtQuerySystemInformation
SetPriorityClass       是   NtSetInformationProcess
GetPriorityClass       是   NtQueryInformationProcess
GetProcessAffinityMask 是   NtQueryInformationProcess
SetProcessAffinityMask 是   NtSetInformationProcess
SetProcessPriorityBoost是   NtSetInformationProcess
GetProcessPriorityBoost是   NtQueryInformationProcess
GetProcessIoCounters   是   NtQueryInformationProcess
GetProcessHandleCount  是   NtQueryInformationProcess
GetProcessWorkingSetSize是  NtQueryInformationProcess
SetProcessWorkingSetSize是  NtSetInformationProcess
GetSystemRegistryQuota  是  NtQuerySystemInformation
IsWow64Process          是  NtQueryInformationProcess



3#
FreeMagnet 发表于 2026-8-23 14:30
4#
lybide 发表于 2026-9-20 09:37
5#
冥界3大法王 发表于 2026-9-20 20:53
搞得多了,忘记了。。。上次重新编译升级的那个叫啥想不起来了。。。
6#
 楼主| summer581 发表于 2026-9-21 18:30 |楼主
冥界3大法王 发表于 2026-9-20 20:53
搞得多了,忘记了。。。上次重新编译升级的那个叫啥想不起来了。。。

什么意思?
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-11-19 05:45

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表