【C#.net】Winform判断指定路径的程序是否已经打开,不区分32位或64位
|
admin
2025年6月2日 16:53
本文热度 668
|
一、在C#中判断指定路径的程序是否已经运行(不区分32/64位)
可以通过以下步骤实现:
获取系统中所有进程
获取每个进程的主模块路径
与目标路径比较(忽略大小写和路径格式差异)
以下是完整代码示例:
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、路径规范化处理:
2、异常处理:
跳过系统/权限不足的进程(Win32Exception)
忽略已退出的进程(InvalidOperationException)
跳过非托管进程(NotSupportedException)
3、比较优化:
4、资源释放:
注意事项:
需要管理员权限才能访问所有进程信息
对于UWP/Store应用可能不适用
路径比较时考虑到了不同格式(如长短路径、大小写)
支持32/64位混合环境
如果遇到权限问题,可在应用程序清单文件(app.manifest)中添加:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
二、如果此程序已经打开,则强制将此程序终止退出
代码如下:
using System;
using System.Diagnostics;
using System.IO;
using System.ComponentModel;
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);
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()
:
2、增强的错误处理:
3、操作反馈:
显示终止进程的名称和PID
提供未找到进程的提示
包含权限错误的详细说明
4、使用示例:
先检查进程是否运行
终止后二次验证确保操作成功
提供清晰的状态反馈
使用注意事项:
1、管理员权限:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
没有管理员权限可能无法终止系统进程或其他用户进程
2、路径规范:
支持长路径和短路径
自动处理路径大小写差异
兼容不同格式的路径分隔符
3、特殊场景处理:
会终止所有匹配路径的进程实例
处理进程树(如需保留子进程需额外处理)
等待进程完全退出后再继续执行
4、替代方案建议(如果权限问题无法解决):
Process.GetProcessesByName("MyProgram")
.ToList()
.ForEach(p => p.Kill());
此代码适用于需要强制终止指定应用程序的场景,如安装/更新程序前的清理操作,或解决程序卡死问题。
该文章在 2025/6/2 16:55:50 编辑过