views:

189

answers:

5

Hello, I open the application using the Process class:

System.Diagnostics.Process vsProc = new System.Diagnostics.Process();
vsProc.StartInfo.FileName = "program.exe";
vsProc.Start();

If I just kill it vsProc.Kill() the application ends uncorrectly. How can I close it correctly? Thanks

+2  A: 

How to close a program 'correctly' depends 100% on the program you're dealing with. If you're the one writing the child program, you get to implement proper & sane behavior. If not, your best general bet is finding the application's main window and send it a close request... rather than terminating the process.

snemarch
A: 

If you need to wait for the application to finish its job and then continue with the parent process, then you can call WaitForExit() on it. If it is a non-terminating app then what do you mean by it 'ends incorrectly'?

Mohit Chakraborty
+1  A: 

I think part of the reason it is ending incorrectly is that you have not freed all of the resources associated with it prior to killing it. Try using the CloseMainWindow()and Close() methods. CloseMainWindow will send a close message to the specified applicaitions main window, and Close() should free resources associated with the process.

John T
A: 

vsProc.Close();

Frees all resources associated with this component. Also get JetBrains ReSharper...

James Oltmans
What does resharper have to do with anything?
Paul Stovell
It makes it easier to find these methods.
James Oltmans
A: 

Assuming that vsProc has a main window and will cleanly end the program if the window is closed, you could use the steps here. If you don't know the title or the title is dynamic, use vsProc.MainWindowTitle. You can skip the FindWindow step by just making a call to vsProc.MainWindowHandle and using the resulting value to call the SendMessage command.