Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct EventHandler to tell me when notepad closed

Tags:

c#

I have the following:

class Program {

    static void Main(string[] args) {

        Process pr;
        pr = new Process();
        pr.StartInfo = new ProcessStartInfo(@"notepad.exe");
        pr.Disposed += new EventHandler(YouClosedNotePad);
        pr.Start();

        Console.WriteLine("press [enter] to exit");
        Console.ReadLine();
    }
    static void YouClosedNotePad(object sender, EventArgs e) {
        Console.WriteLine("thanks for closing notepad");
    }

}

When I close Notepad I don't get the message I was hoping to get - how do I amend so that closing notepad is returned to the console?

like image 429
whytheq Avatar asked May 10 '26 21:05

whytheq


1 Answers

You need two things - enable raising events, and subscribing to Exited event:

    static void Main(string[] args)
    {            
        Process pr;
        pr = new Process();
        pr.StartInfo = new ProcessStartInfo(@"notepad.exe");
        pr.EnableRaisingEvents = true; // first thing
        pr.Exited += pr_Exited; // second thing
        pr.Start();

        Console.WriteLine("press [enter] to exit");
        Console.ReadLine();

        Console.ReadKey(); 
    }

    static void pr_Exited(object sender, EventArgs e)
    {
        Console.WriteLine("exited");
    }
like image 72
Sergey Berezovskiy Avatar answered May 12 '26 11:05

Sergey Berezovskiy