[英]check in realtime an external process when open a file
如果特定进程尝试读取 flac 文件的 wav,我需要实时检查。
我创建了一个带有 2 个参数的例程:进程名称和尝试打开的文件:
public static bool Scan(string ProcessName,string TextToFind)
{
// getting minimum & maximum address
SYSTEM_INFO sys_info = new SYSTEM_INFO();
GetSystemInfo(out sys_info);
int MatchCount=0;
IntPtr proc_min_address = sys_info.minimumApplicationAddress;
IntPtr proc_max_address = sys_info.maximumApplicationAddress;
// saving the values as long ints so I won't have to do a lot of casts later
long proc_min_address_l = (long)proc_min_address;
long proc_max_address_l = (long)proc_max_address;
Process[] Arrprocess = Process.GetProcessesByName(ProcessName);
if (Arrprocess.Length == 0) return false;
// notepad better be runnin'
Process process = Arrprocess[0];
// opening the process with desired access level
IntPtr processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, process.Id);
// this will store any information we get from VirtualQueryEx()
MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION();
int bytesRead = 0; // number of bytes read with ReadProcessMemory
// long milliseconds_start = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
while (proc_min_address_l < proc_max_address_l)
{
// 28 = sizeof(MEMORY_BASIC_INFORMATION)
VirtualQueryEx(processHandle, proc_min_address, out mem_basic_info, 28);
// if this memory chunk is accessible
if (mem_basic_info.Protect == PAGE_READWRITE && mem_basic_info.State == MEM_COMMIT && (mem_basic_info.lType == MEM_MAPPED || mem_basic_info.lType == MEM_PRIVATE))
{
byte[] buffer = new byte[mem_basic_info.RegionSize];
// read everything in the buffer above
ReadProcessMemory((int)processHandle, mem_basic_info.BaseAddress, buffer, mem_basic_info.RegionSize, ref bytesRead);
string result = System.Text.Encoding.ASCII.GetString(buffer);
if (result.Contains(TextToFind))
return true;
}
// move to the next memory chunk
proc_min_address_l += mem_basic_info.RegionSize;
proc_min_address = new IntPtr(proc_min_address_l);
}
return false;
}
这段代码只在第一次工作,因为当进程关闭 flac 文件时,字符串会保留在内存中,直到进程关闭。
我需要每次(以毫秒为精度)检查进程尝试加载我作为参数传递的文件。
我不知道我是否走对了路...
有人可以向我推荐一个代码(在 c# 或 c++ 中),它可以实时检测进程 x 是否尝试读取文件名 y ?
谢谢 !
Windows 提供了让您知道文件何时被打开/编辑/重命名/等的方法。
https://docs.microsoft.com/en-us/windows/win32/projfs/file-system-operation-notifications
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.