views:

418

answers:

4

I'm looking for a way to shutdown a windows app from another. Is there a way to do this?

Ideally I'd like something that basically mimics an ALT-F4, or pressing the 'X' in the top right corner or some such.

Alternatively, is there an application out there that does this already? tskill is a bit too harsh for what I have in mind.

+5  A: 

According to your description this sounds like a windowed app. In that case you can send it a WM_CLOSE message to mimic the behavior when pressing the "X" button.

Another alternative is to use TerminateProcess, but this is probably what tskill does as well.

On Freund
Well, basically I want it to shutdown *any* app, elegantly if possible. This can be windowed apps, console apps, whatever. Is there an equivalent to that for console apps?
Eddie Parker
Windowed apps have a message loop which you can use to your advantage. With console apps, there's no generic solution other than the brute force TerminateProcess.
On Freund
+1  A: 

I'll first refer you to my answer to another question; although it was about Delphi and services, the answer is neither Delphi- nor service-specific. In short, there is no generic way to gracefully stop a program. The accepted answer for that question demonstrates posting a wm_Close message to a program's window.

Rob Kennedy
+5  A: 

EDIT: I did a little digging and found a MSDN Article with the Microsoft recommended approach.

Since this is a windows app you can send the WM_CLOSE message to the main window however keep in mind that if the application overrides handling of the WM_CLOSE message you may get unexpected results. Also keep in mind that use of win32 functions like TerminateProcess and ExitProcess can also have unpleasant side-effects (see the remarks sections on msdn) including global data in dll's getting compromised as well as deadlocks.

If you are responsible for having coded the target application I would recommend adding some form of built in termination mechanism that can be triggered externally (e.g. magic packet on the loopback address or pipes) that way you can be sure your application has cleaned up after itself appropriately.

Kevin Loney
The link to the MSDN article deserves an answer of its own so I can vote it up...
itsadok
+1  A: 

More powerful command to close app is:

 PostMessage (myhnd,WM_ENDSESSION,TRUE,ENDSESSION_LOGOFF);
Tom