LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

【C#.net】Winform判断指定路径的程序是否已经打开,不区分32位或64位

admin
2025年6月2日 16:53 本文热度 411

一、在C#中判断指定路径的程序是否已经运行(不区分32/64位)

可以通过以下步骤实现:

  1. 获取系统中所有进程

  2. 获取每个进程的主模块路径

  3. 与目标路径比较(忽略大小写和路径格式差异)

以下是完整代码示例:

using System;

using System.Diagnostics;

using System.IO;

using System.Linq;

using System.Runtime.InteropServices;


public class ProcessChecker

{

    public static bool IsProcessRunning(string targetPath)

    {

        // 规范化为绝对路径

        string fullTargetPath = Path.GetFullPath(targetPath).TrimEnd('\\');


        foreach (var process in Process.GetProcesses())

        {

            try

            {

                // 跳过无主模块的进程

                if (process.MainModule == null) continue;


                string processPath = Path.GetFullPath(process.MainModule.FileName).TrimEnd('\\');

                

                // 路径比较(不区分大小写)

                if (string.Equals(processPath, fullTargetPath, StringComparison.OrdinalIgnoreCase))

                {

                    return true;

                }

            }

            catch (Exception ex) when (ex is Win32Exception || ex is InvalidOperationException || ex is NotSupportedException)

            {

                // 跳过权限不足或无法访问的进程

                continue;

            }

            finally

            {

                process.Dispose();

            }

        }

        return false;

    }


    // 使用示例

    public static void Main()

    {

        string exePath = @"C:\Program Files\MyApp\MyProgram.exe";

        bool isRunning = IsProcessRunning(exePath);

        

        Console.WriteLine(isRunning 

            ? $"程序已在运行: {exePath}" 

            : $"程序未运行: {exePath}");

    }

}

关键点说明:

1、路径规范化处理:

  • 使用Path.GetFullPath()统一路径格式

  • TrimEnd('\\')消除尾部反斜杠差异

2、异常处理:

  • 跳过系统/权限不足的进程(Win32Exception)

  • 忽略已退出的进程(InvalidOperationException)

  • 跳过非托管进程(NotSupportedException)

3、比较优化:

  • 使用StringComparison.OrdinalIgnoreCase进行大小写不敏感比较

  • 直接比较完整路径而非进程名称

4、资源释放:

  • 在finally块中调用process.Dispose()释放资源

注意事项:

  • 需要管理员权限才能访问所有进程信息

  • 对于UWP/Store应用可能不适用

  • 路径比较时考虑到了不同格式(如长短路径、大小写)

  • 支持32/64位混合环境

如果遇到权限问题,可在应用程序清单文件(app.manifest)中添加:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />


二、如果此程序已经打开,则强制将此程序终止退出

代码如下:

using System;

using System.Diagnostics;

using System.IO;

using System.ComponentModel; // 用于Win32Exception


public class ProcessManager

{

    public static bool IsProcessRunning(string targetPath)

    {

        string fullTargetPath = Path.GetFullPath(targetPath).TrimEnd('\\');


        foreach (var process in Process.GetProcesses())

        {

            try

            {

                if (process.MainModule == null) continue;

                

                string processPath = Path.GetFullPath(process.MainModule.FileName).TrimEnd('\\');

                

                if (string.Equals(processPath, fullTargetPath, StringComparison.OrdinalIgnoreCase))

                {

                    return true;

                }

            }

            catch (Exception ex) when (ex is Win32Exception || ex is InvalidOperationException)

            {

                // 跳过无权限访问的进程

            }

            finally

            {

                process.Dispose();

            }

        }

        return false;

    }


    public static void KillProcessByPath(string targetPath)

    {

        string fullTargetPath = Path.GetFullPath(targetPath).TrimEnd('\\');

        bool found = false;


        foreach (var process in Process.GetProcesses())

        {

            try

            {

                if (process.MainModule == null) continue;

                

                string processPath = Path.GetFullPath(process.MainModule.FileName).TrimEnd('\\');

                

                if (string.Equals(processPath, fullTargetPath, StringComparison.OrdinalIgnoreCase))

                {

                    process.Kill();

                    process.WaitForExit(3000); // 等待最多3秒

                    found = true;

                    Console.WriteLine($"已终止进程: {process.ProcessName} (PID: {process.Id})");

                }

            }

            catch (Win32Exception ex)

            {

                Console.WriteLine($"权限不足,无法终止进程 {process.ProcessName}: {ex.Message}");

            }

            catch (InvalidOperationException)

            {

                // 进程已退出,忽略

            }

            catch (Exception ex)

            {

                Console.WriteLine($"终止进程 {process.ProcessName} 时出错: {ex.Message}");

            }

            finally

            {

                process.Dispose();

            }

        }


        if (!found)

        {

            Console.WriteLine($"未找到运行中的进程: {Path.GetFileName(targetPath)}");

        }

    }


    // 使用示例

    public static void Main()

    {

        string exePath = @"C:\Program Files\MyApp\MyProgram.exe";

        

        if (IsProcessRunning(exePath))

        {

            Console.WriteLine("程序正在运行,即将强制终止...");

            KillProcessByPath(exePath);

            

            // 二次验证

            if (!IsProcessRunning(exePath))

            {

                Console.WriteLine("程序已成功终止");

            }

            else

            {

                Console.WriteLine("程序终止失败");

            }

        }

        else

        {

            Console.WriteLine("程序未运行");

        }

    }

}

关键功能说明:

1、进程终止方法 KillProcessByPath()

  • 遍历所有进程,匹配目标路径的程序

  • 使用process.Kill()强制终止进程

  • 调用WaitForExit(3000)等待进程退出(最多3秒)

2、增强的错误处理

  • Win32Exception:处理权限不足问题

  • InvalidOperationException:处理进程已退出的情况

  • 通用异常捕获:确保程序不会意外崩溃

3、操作反馈

  • 显示终止进程的名称和PID

  • 提供未找到进程的提示

  • 包含权限错误的详细说明

4、使用示例

  • 先检查进程是否运行

  • 终止后二次验证确保操作成功

  • 提供清晰的状态反馈

使用注意事项:

1、管理员权限

// 在app.manifest中添加以下内容

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

没有管理员权限可能无法终止系统进程或其他用户进程

2、路径规范

  • 支持长路径和短路径

  • 自动处理路径大小写差异

  • 兼容不同格式的路径分隔符

3、特殊场景处理

  • 会终止所有匹配路径的进程实例

  • 处理进程树(如需保留子进程需额外处理)

  • 等待进程完全退出后再继续执行

​4、替代方案建议(如果权限问题无法解决):

// 使用进程名终止(需确保进程名唯一)

Process.GetProcessesByName("MyProgram")

    .ToList()

    .ForEach(p => p.Kill());

此代码适用于需要强制终止指定应用程序的场景,如安装/更新程序前的清理操作,或解决程序卡死问题。


该文章在 2025/6/2 16:55:50 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved