C# 进程终止通知
C# Process Termination notifications
我目前正在寻找一种在特定进程关闭时删除特定文件的方法。我找到了很多创建进程和为 exited
添加事件处理程序的示例,但我需要收到系统中所有进程的通知,而不仅仅是我创建的进程。
谁能阐明这是如何实现的?
我对你的问题很感兴趣,所以我为此写了一个小应用程序,希望你觉得它有用。可以在很多方面进行改进:)
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);
}
}
我目前正在寻找一种在特定进程关闭时删除特定文件的方法。我找到了很多创建进程和为 exited
添加事件处理程序的示例,但我需要收到系统中所有进程的通知,而不仅仅是我创建的进程。
谁能阐明这是如何实现的?
我对你的问题很感兴趣,所以我为此写了一个小应用程序,希望你觉得它有用。可以在很多方面进行改进:)
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);
}
}