[英]C# Process Termination notifications
I am currently looking for a way to delete a certain file when a specific process has closed.我目前正在寻找一种在特定进程关闭时删除某个文件的方法。 I've found plenty of examples for creating a process and adding an event handler for exited
but I need to get notified of any processes in the system, not just those I create.我找到了很多创建进程和为exited
添加事件处理程序的示例,但我需要收到系统中任何进程的通知,而不仅仅是我创建的进程。
Can anyone shed light on how this could be accomplished?任何人都可以阐明如何实现这一目标吗?
I was very interested in your question so I wrote a little app for it, hopefully you find it useful.我对你的问题很感兴趣,所以我为它写了一个小应用程序,希望你觉得它有用。 Can be improved in a lot of ways :)可以在很多方面改进:)
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.