close external application before closing the main application

4.7k views Asked by At

I am working on development of a plugin writing in c# winforms for an application. I have set up a start action in debug. I have set start external program and it is starting that application. In my winforms I have written code for a button click event which starts a new process say notepad.exe

Now the question is whenever I close that external application all the opened notepad which are invoked from this button click event should be closed automatically.

Any help can be appreciated.

2

There are 2 answers

1
Gleb On

You can use System.Diagnostics.Process to start process, like this:

Process proc=Process.Start("notepad.exe");

And in Closing event you can use:

proc.Kill;

Also you can store just an id of your processes:

//arr is int array where stored your processes ids
for(int i=0; i<arr.Length; i++)
{
    Process.GetProcessById(arr[i]).Kill();
}
2
Idle_Mind On

In this example, I close Notepad when Calculator is closed:

    private void Form1_Load(object sender, EventArgs e)
    {
        foreach (Process p in Process.GetProcessesByName("calc"))
        {
            p.EnableRaisingEvents = true;
            p.Exited += p_Exited;
        }
    }

    void p_Exited(object sender, EventArgs e)
    {
        foreach (Process p in Process.GetProcessesByName("notepad"))
        {
            p.CloseMainWindow();
        }
    }