0

I have an application that launches another program and monitors it. When the program closes, my application also closes.

However, if I close my application first, the other program is still running.

ProcessStartInfo procInfo = new ProcessStartInfo("myProg.exe");
Process proc = new Process();
proc.StartInfo = procInfo;
proc.Start();

while (!proc.HasExited)
{
    // do stuff
}

// On proc exit, my application is also done

How do I make sure that if I close my monitoring app, any processes that are being monitored are also killed?

So for example suppose MyApp is monitoring Notepad. If I close MyApp, Notepad should also be closed.

MxLDevs
  • 19,048
  • 36
  • 123
  • 194
  • 1
    Hook the `OnClose` or `OnUnload` event of your main form, and kill the process that you are monitoring. – Robert Harvey Apr 02 '14 at 19:52
  • Is this a Console or Form application? That will make a large difference into what you need to do in order to detect that your app is being exited. – Ben Black Apr 02 '14 at 19:53
  • Console, though I am planning to create a form application so both would be nice to know. For the purposes of this question it is a console app. – MxLDevs Apr 02 '14 at 19:54
  • FWIW, the proper way to do this is to use a Windows Job Object (this will require PInvoke). – EricLaw Apr 02 '14 at 20:10

2 Answers2

0

At that end of your program call:

if (!proc.HasExited)
    proc.CloseMainWindow();

... to close the other process's window.

noelicus
  • 14,468
  • 3
  • 92
  • 111
  • It is what he asked: he wants to close the *other* process's window. The other process being "proc". – noelicus Apr 02 '14 at 20:10
  • Yes; but not if he closes his application first which he also wanted. – Ben Black Apr 02 '14 at 20:12
  • Evidently, his question was in fact: "how can I detect a console application is being closed" and not how to kill a monitored process. I read it mainly as the latter. – noelicus Apr 02 '14 at 20:16
0

Since this is a console application, capturing the "Exit" event is a bit trickier than forms. Take a look at this thread, I have it bookmarked because I was wondering the same thing as you a long time ago and it's handy to keep this around.

Community
  • 1
  • 1
Ben Black
  • 3,751
  • 2
  • 25
  • 43