我目前正在寻找一种在特定进程关闭时删除某个文件的方法。我已经找到了很多用于创建进程和为exited
添加事件处理程序的示例,但我需要获得系统中任何进程的通知,而不仅仅是我创建的进程。
有人能说明如何实现这一目标吗?
答案 0 :(得分:2)
我对你的问题很感兴趣,所以我为它写了一个小应用程序,希望你发现它很有用。可以通过很多方式进行改进:)
class Program
{
private static readonly List<Process> AllProcesses = new List<Process>();
static void Main(string[] args)
{
var timer = new Timer(1000);
timer.AutoReset = true;
timer.Elapsed += (sender, eventArgs) =>
{
Process[] processSnapShot = Process.GetProcesses();
var newProcesses = processSnapShot.Where(p => !AllProcesses.Select(p2 => p2.Id).Contains(p.Id));
WireHandler(newProcesses);
AllProcesses.AddRange(newProcesses);
};
var processes = Process.GetProcesses();
WireHandler(processes);
timer.Start();
Console.ReadLine();
}
private static void WireHandler(IEnumerable<Process> processes)
{
foreach (var process in processes)
{
try
{
Console.WriteLine("Process started " + process.ProcessName);
process.EnableRaisingEvents = true;
process.Exited += ProcessOnExited;
}
catch (Exception e)
{
Console.WriteLine("Error occurred " + e.Message);
}
}
}
private static void ProcessOnExited(object sender, EventArgs eventArgs)
{
var process = (Process) sender;
AllProcesses.Remove(process);
Console.WriteLine("Process exited " + process.ProcessName);
}
}