C#进程管理程序

1.功能

鼠标点到应用图标,显示该进程号,并可以强制关闭此进程

2.程序

复制代码
using System;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace ProcessKiller
{
    public partial class MainForm : Form
    {
        // Windows API 导入
        [DllImport("user32.dll")]
        private static extern IntPtr WindowFromPoint(Point point);

        [DllImport("user32.dll")]
        private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);

        [DllImport("user32.dll")]
        private static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder text, int count);

        [DllImport("user32.dll")]
        private static extern int GetWindowTextLength(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern bool IsWindowVisible(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern IntPtr GetShellWindow();

        // 控件声明
        private Label lblStatus;
        private Button btnKill;
        private Button btnRefresh;
        private ListBox lstProcesses;
        private Timer timer;

        private uint selectedProcessId = 0;

        public MainForm()
        {
            InitializeComponent();
            StartMouseHook();
        }

        private void InitializeComponent()
        {
            this.Text = "进程终结者 - 点击图标显示PID并强制关闭";
            this.Size = new Size(400, 500);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.TopMost = true;

            // 状态标签
            lblStatus = new Label()
            {
                Location = new Point(12, 12),
                Size = new Size(360, 50),
                Text = "将鼠标移动到任意窗口或任务栏图标上...",
                BackColor = Color.LightYellow,
                BorderStyle = BorderStyle.FixedSingle
            };

            // 进程列表
            lstProcesses = new ListBox()
            {
                Location = new Point(12, 70),
                Size = new Size(360, 300),
                Font = new Font("Consolas", 9)
            };

            // 关闭按钮
            btnKill = new Button()
            {
                Text = "强制关闭选中的进程",
                Location = new Point(12, 380),
                Size = new Size(170, 40),
                BackColor = Color.IndianRed,
                Enabled = false
            };
            btnKill.Click += BtnKill_Click;

            // 刷新进程列表按钮
            btnRefresh = new Button()
            {
                Text = "刷新进程列表",
                Location = new Point(202, 380),
                Size = new Size(170, 40),
                BackColor = Color.LightBlue
            };
            btnRefresh.Click += BtnRefresh_Click;

            // 定时器用于实时更新鼠标下的进程信息
            timer = new Timer();
            timer.Interval = 200; // 200毫秒检测一次
            timer.Tick += Timer_Tick;

            this.Controls.Add(lblStatus);
            this.Controls.Add(lstProcesses);
            this.Controls.Add(btnKill);
            this.Controls.Add(btnRefresh);
        }

        private void StartMouseHook()
        {
            timer.Start();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            Point cursorPos = Control.MousePosition;
            IntPtr hWnd = WindowFromPoint(cursorPos);

            if (hWnd != IntPtr.Zero)
            {
                // 获取窗口标题
                int textLen = GetWindowTextLength(hWnd);
                string windowTitle = "";
                if (textLen > 0)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder(textLen + 1);
                    GetWindowText(hWnd, sb, sb.Capacity);
                    windowTitle = sb.ToString();
                }

                // 获取进程ID
                GetWindowThreadProcessId(hWnd, out uint pid);

                // 更新状态栏
                if (pid > 0)
                {
                    try
                    {
                        Process proc = Process.GetProcessById((int)pid);
                        string processName = proc.ProcessName;
                        lblStatus.Text = $"当前指向: {windowTitle} (窗口句柄: {hWnd})\n进程名: {processName}  PID: {pid}";
                        selectedProcessId = pid;
                        btnKill.Enabled = true;
                    }
                    catch
                    {
                        lblStatus.Text = $"指向对象无法获取进程信息 (PID: {pid})";
                        selectedProcessId = 0;
                        btnKill.Enabled = false;
                    }
                }
                else
                {
                    lblStatus.Text = $"指向: {windowTitle} (无法获取进程ID)";
                    selectedProcessId = 0;
                    btnKill.Enabled = false;
                }
            }
        }

        private void BtnKill_Click(object sender, EventArgs e)
        {
            if (selectedProcessId == 0)
            {
                MessageBox.Show("没有选中的进程", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                Process processToKill = Process.GetProcessById((int)selectedProcessId);
                DialogResult result = MessageBox.Show(
                    $"确定要强制关闭进程 \"{processToKill.ProcessName}\" (PID: {selectedProcessId}) 吗?\n\n这将立即终止该进程及其所有线程。",
                    "确认关闭",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Warning);

                if (result == DialogResult.Yes)
                {
                    processToKill.Kill();
                    processToKill.WaitForExit(1000);
                    MessageBox.Show($"进程 {processToKill.ProcessName} (PID: {selectedProcessId}) 已被终止。", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    selectedProcessId = 0;
                    btnKill.Enabled = false;
                    BtnRefresh_Click(null, null); // 刷新列表
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法终止进程: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                selectedProcessId = 0;
                btnKill.Enabled = false;
            }
        }

        private void BtnRefresh_Click(object sender, EventArgs e)
        {
            lstProcesses.Items.Clear();
            Process[] processes = Process.GetProcesses();
            foreach (Process proc in processes)
            {
                try
                {
                    string title = string.IsNullOrEmpty(proc.MainWindowTitle) ? "[无窗口]" : proc.MainWindowTitle;
                    lstProcesses.Items.Add($"{proc.ProcessName,-30} PID:{proc.Id,-8} 窗口:{title}");
                }
                catch
                {
                    lstProcesses.Items.Add($"{proc.ProcessName,-30} PID:{proc.Id,-8} [无法获取窗口信息]");
                }
            }
            lstProcesses.Items.Add("----------------------------------------------");
            lstProcesses.Items.Add("提示: 将鼠标移动到任务栏图标或窗口上即可检测");
        }

        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            timer.Stop();
            base.OnFormClosed(e);
        }
    }

    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}

3.使用方法与功能说明:

  1. 实时检测:程序运行后,将鼠标移动到任何窗口标题栏或任务栏图标上,状态栏会立即显示该窗口的标题、所属进程名称和进程ID (PID)。

  2. 强制关闭

    • 当鼠标指向一个可识别的进程窗口时,窗口底部的"强制关闭选中的进程"按钮会被启用。

    • 点击该按钮后,程序会弹出确认对话框,确认后将立即终止该进程。

    • 注意:关闭系统关键进程(如explorer.exe、csrss.exe等)可能导致系统不稳定,请谨慎操作。

  3. 进程列表:右侧的进程列表显示了当前系统中所有正在运行的进程及其PID,方便您查看和选择。

4.核心API说明:

  • WindowFromPoint:获取鼠标当前位置的窗口句柄。

  • GetWindowThreadProcessId:通过窗口句柄获取对应的进程ID。

  • Process.Kill():立即终止进程(强制关闭)。

相关推荐
凡人叶枫1 小时前
Effective C++ 条款28:避免使用 handles 指向对象内部
linux·服务器·开发语言·c++·嵌入式开发
努力成为AK大王2 小时前
并发编程的核心挑战、优化方案与核心知识点总结
java·开发语言·数据库
AI 编程助手GPT2 小时前
用 Python 做一个世界杯赛前分析脚本:以巴西 vs 摩洛哥为例
开发语言·网络·人工智能·python·chatgpt
lihao lihao2 小时前
Linux信号
开发语言·c++·算法
Java患者·3 小时前
《Python 人脸识别入门实践:从人脸检测到人脸比对完整实现》
开发语言·python·opencv·目标检测·计算机视觉·目标跟踪·视觉检测
ceclar1233 小时前
C# 的任务并行库(TPL)
开发语言·c#·.net
快乐的哈士奇3 小时前
【Next.js实战①】Gmail API 按柜号检索邮件:OAuth 双 Cookie 与搜索 Fallback
开发语言·javascript·ecmascript
weixin_307779133 小时前
Python写入Shell文件使用Linux系统的换行符
linux·开发语言·python·自动化
hhcgchpspk3 小时前
汇编语言传递数据和地址的误区
汇编·笔记·nasm·masm