Windows句柄、进程和被占用文件路径之间的操作
1、由进程判断指定文件夹及文件是否被占用
using System;
using System.Diagnostics;
namespace Windows
{
public class EnumWindowsApp
{
public void EnumWindowsApps()
{
string targetPath = Environment.CurrentDirectory;
Process[] processes = Process.GetProcesses();
for (int i = 0; i < processes.GetLength(0); i++)
{
try
{
Process process = Process.GetCurrentProcess();
#region 通过目标路径判断目标路径是否有程序启动
string processFilePath = processes[i].MainModule.FileName;
processFilePath = processFilePath.Substring(0, processFilePath.IndexOf(processFilePath.Split('\\')[processFilePath.Split('\\').GetLength(0) - 1]));
//如果当前路径存在 在系统进程中
if (targetPath.Equals(processFilePath))
{
//通过反射取得当前进程中的非公共成员
System.Reflection.FieldInfo fieldInfo = processes[i].GetType().GetField("processInfo", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
dynamic processInfo = fieldInfo.GetValue(processes[i]);
//取得进程id
int processId = processInfo.processId;
//目标目录内的文件被当前进程所占用 如有需求 可杀掉进程
//processes[i].Kill();
}
#endregion
}
catch (Exception)
{
}
}
}
}
}
2、由句柄判断指定文件夹及文件是否被占用
using System; using System.Diagnostics; using System.Runtime.InteropServices; public delegate bool CallBack(int hwnd, int lParam); namespace Windows { public class EnumWindowsApp { [DllImport("user32")] public static extern int EnumWindows(CallBack x, int y); public static void Main() { CallBack myCallBack = new CallBack(EnumWindowsApp.Excute); EnumWindows(myCallBack, 0); } /// <summary> /// 开始逐个遍历 Windows 句柄 并取得句柄的进程和路径 /// </summary> public static bool Excute(int hwnd, int lParam) { //获得当前句柄对应的程序进程 Process process = GetProcessPath(new IntPtr(hwnd)); //获取当前句柄对应进程的文件路径 string appPath = process?.MainModule.FileName; return true; } [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern int GetWindowThreadProcessId(IntPtr handle, out uint processId); public static Process GetProcessPath(IntPtr hwnd) { Process process = null; try { uint pid = 0; GetWindowThreadProcessId(hwnd, out pid); //由进程ID得到进程 process = Process.GetProcessById((int)pid); //此处会失败,会报出 程序以32位平台运行时取64位程序的进程路径会异常 故用try catch块儿包起来 _ = process.MainModule.FileName; } catch (Exception) { } return process; } } }
本文作者:Journey&Flower
本文链接:https://www.cnblogs.com/JourneyOfFlower/p/15004987.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步