I’m new to programming. I have a form application that launches a thread. Form there 4 new threads are launched. Each of these threads performs a series of command line processes like the following:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WorkingDirectory ="C:\\BLA\\bin_windows";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.CreateNoWindow = true;
startInfo.FileName = "SomeProcess"
Process p = Process.Start(startInfo);
p.WaitForExit();
When the form application is closed it aborts the first thread (not the 4 separate ones).
Now my question is how to force the processes “p” to quit when I close the form??
I tried the following:
foreach (Process p in System.Diagnostics.Process.GetProcessesByName("SomeProcess"))
{
try
{
p.Kill();
p.WaitForExit(); // possibly with a timeout
}
catch
{ continue; }
}
However, this approach seems a little brutal to me and does not always work well… Is there a way that I can identify only the processes that Ive launched myself and then terminate them?
Any suggestions greatly appreciated.
Thanks
You have very little control of processes you have run. Killing them is one way. If the process is a windowed application (i.e. has a window) you can try sending it a
WM_CLOSEmessage which is equivalent of clicking a close button on the window. Again, application must have a window, either visible or hidden and because of that it will not work on every application. Most applications do have windows though even if not visible.To kill/close only processes you have spawned just keep their
Processobjects or at leastp.MainWindowHandleif you want to use approach I gave you. For that, have a public property of typeConcurrentBag<Process>(orConcurrentBag<IntPtr>) in your class. It is already thread safe.EDIT
As someone pointed out you can do this to close process’ main window: