20

I want to start a new process B.exe from the current executing process A.exe.

And as soon as B.exe is launched I want to kill A.exe (the current executing process).

Though I can start B.exe I cannot close my current process i.e A.exe.

Code I use is:

//Start the BT Setup Process
ProcessStartInfo startInfo = new ProcessStartInfo(@"C:\TEST\B.exe");
Process.Start(startInfo);

//Terminate the FSA 
Process[] myProcess = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);
foreach (Process process in myProcess)
{
    process.CloseMainWindow();
    //all the windows messages has to be processed in the msg queue
    //hence call to Application DoEvents forces the MSG
    Application.DoEvents();
}
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
srivatsa
  • 219
  • 1
  • 2
  • 3

5 Answers5

10

Why do you want to close A from B while A cat start B and then close by itself?

Process.Start("A.exe");
Process.GetCurrentProcess().Kill(); // or Application.Exit(); or anything else
abatishchev
  • 98,240
  • 88
  • 296
  • 433
7

If you're falling into this quest of starting a process, and kill your own process after, use Environment.Exit(0), not Application.Exit().

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Fabiano Cores
  • 189
  • 1
  • 2
  • 2
    The application will not exit if there are any active foreground threads; Process.GetCurrentProcess().Kill(); seems more deterministic. – Erwin Mayer Nov 01 '15 at 19:14
  • 1
    This is very important... because, there's times where you do not want to kill threads... right? And sometimes you do! – Fabiano Cores Oct 08 '16 at 17:15
3

I know this is old but in .net 4.0 you can do

ProcessStartInfo startInfo = new ProcessStartInfo(@"C:\TEST\B.exe");
startInfo.UseShellExecute = true;//This should not block your program
Process.Start(startInfo);

Then Application.Exit or whatever I tested with a winforms application using the close form method after launching a console app that just blocks on Console.readline();

3

Try Process.Kill() instead of Process.CloseMainWindow().

Colin Pickard
  • 45,724
  • 13
  • 98
  • 148
2

If you just want to close the current process you should be able to just call Application.Exit rather than looping through and closing processes.

Hans Olsson
  • 54,199
  • 15
  • 94
  • 116
  • Using Application.Exit hangs my A.exe application. That is the reason i use Process.CloseMainWindow() – srivatsa Nov 25 '10 at 16:17
  • 4
    @srivatsa: If calling `Application.Exit` in your process makes it hang, then I'd say that it might be worth trying to find out why, that might automatically answer your question above as well. – Hans Olsson Nov 25 '10 at 16:35