Eddie Parker
Eddie Parker

Reputation: 4888

Win32 API For Shutting Down Another Process Elegantly?

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.

Upvotes: 1

Views: 1499

Answers (4)

Kevin Loney
Kevin Loney

Reputation: 7553

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.

Upvotes: 5

Tom
Tom

Reputation: 6707

More powerful command to close app is:

    PostMessage (myhnd,WM_ENDSESSION,TRUE,ENDSESSION_LOGOFF);

Upvotes: 2

Rob Kennedy
Rob Kennedy

Reputation: 163277

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.

Upvotes: 1

On Freund
On Freund

Reputation: 4436

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.

Upvotes: 4

Related Questions