Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process.Close() does not close program

Tags:

c#

Here is the simple program:

class Program {

    static void Main(string[] args) {

        Process pr = new Process();
        ProcessStartInfo prs = new ProcessStartInfo();
        prs.FileName = @"notepad.exe";
        pr.StartInfo = prs;
        pr.EnableRaisingEvents = true;
        pr.Start();

        Thread.Sleep(2000);

        pr.Close(); //how do I change this to close notepad

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

How do I change this so Notepad closes?

like image 771
whytheq Avatar asked Apr 26 '26 15:04

whytheq


2 Answers

According to MSDN, Process.Close() simply:

Frees all the resources that are associated with this component.

Take a look at Process.Kill() and Process.CloseMainWindow()

For this application, I would use:

pr.CloseMainWindow();
pr.Close();
like image 62
James Hill Avatar answered Apr 28 '26 08:04

James Hill


Try with Process.CloseMainWindow() method instead of.

Closes a process that has a user interface by sending a close message to its main window.

Try like this;

Process pr = new Process();
ProcessStartInfo prs = new ProcessStartInfo();
prs.FileName = @"notepad.exe";
pr.StartInfo = prs;
pr.EnableRaisingEvents = true;
pr.Start();

Thread.Sleep(2000);

pr.CloseMainWindow();
pr.Close();

Console.WriteLine("press [enter] to exit");
Console.ReadLine();
like image 43
Soner Gönül Avatar answered Apr 28 '26 07:04

Soner Gönül



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!