Close another process when the application closes.

I have a winform C # application that, during its operation, opens another Winform process. Another process has its own user interface. When I close the parent application, I want another application to be closed automatically.

How can i achieve this?

thanks

+4
source share
3 answers

If you use Process.Process , there is a CloseMainWindow method. If you save a link to an object, you can use it later.

Here is the corresponding page on MSDN

and corresponding code:

 // Close process by sending a close message to its main window. myProcess.CloseMainWindow(); // Free resources associated with process. myProcess.Close(); 
+4
source

There are several different options. I would suggest that you have an application that tracks the processes it runs:

 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 closes all running 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 elegant closure (if you run Notepad and there are unsaved changes, Kill will lose them, CloseMainWindow / Close will make a notepad 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(); } } } 
+3
source

The most elegant way to do this is probably to send a window message to the main one from another process. You can get the handle to this main form simply by using the Process.MainWindow.Handle property (I assume that you are using the Process class, and then just use the PostMessage Win API call to send a message with a user ID to the main window of this "child" process. Then another processโ€™s message loop can easily detect this message (by overriding the WndProc method) and complete the work properly. An alternative would be to send the standard WM_CLOSE method, which would mean you just need to get it Create an application from the Form.Closed event Form.Closed , but it may possibly allow you less control (over whether to cancel the shutdown in certain situations).

+1
source

Source: https://habr.com/ru/post/1285653/


All Articles