C# Process Termination notifications

1.1k views Asked by At

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.

Can anyone shed light on how this could be accomplished?

1

There are 1 answers

0
Ruskin On BEST ANSWER

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);
    }
}