Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close another process when application is closing

Tags:

c#

winforms

I have a C# winform application that during its work opens another Winform process. The other process has UI of its own. When I close the parent application, I want the other application to be closed automatically.

How can I achieve that?

Thanks

like image 250
Ragoler Avatar asked Mar 01 '23 16:03

Ragoler


2 Answers

If you are using Process.Process there is the CloseMainWindow method. If you keep a reference to the object you can use it later.

Here's the relevant page in the MSDN

and the relevant code:

// Close process by sending a close message to its main window.
myProcess.CloseMainWindow();
// Free resources associated with process.
myProcess.Close();
like image 177
ChrisF Avatar answered Mar 07 '23 20:03

ChrisF


There are several different options. I would suggest that you have your application keep track of the processes that it starts:

private Stack<Process> _startedProcesses = new Stack<Process>();
private void StartChildProcess(string fileName)
{
    Process newProcess = new Process();
    newProcess.StartInfo = new ProcessStartInfo(fileName); ;
    newProcess.Start();    
    _startedProcesses.Push(newProcess);
}

When the application closes, you can call a method that will close all started child processes that are still running. You can use this either with the Kill method or by calling the CloseMainWindow and Close methods. CloseMainWindow/Close will perform a more graceful close (if you start Notepad and there are unsaved changes, Kill will lose them, CloseMainWindow/Close will make notepad ask if you want to save):

private void CloseStartedProcesses()
{
    while (_startedProcesses.Count > 0)
    {
        Process process = _startedProcesses.Pop();
        if (process != null && !process.HasExited)
        {
            process.CloseMainWindow();
            process.Close();
        }
    }
}
like image 38
Fredrik Mörk Avatar answered Mar 07 '23 20:03

Fredrik Mörk