简体   繁体   中英

How to detect if my Windows application has ended?

Basically what the title says I need to detect when my program is ending like when someones clicks on end task in the task manager or something. Can anyone point me to some kind of event that handles this with an example or something? Thanks for any help given

You need to open this process. This way you will retrieve its handle. After that you can simply wait on this handle.

HANDLE h = OpenProcess(....);
WaitForSingleObject(h);

Handles of the processes and threads in many ways look like Windows event handles. Once this process or thread finishes, they get signaled.

It depends on how your app is terminated and what type of app it is.

For apps with an UI:

  • If the user clicks "End Task" in the task manager, you will actually receive WM_DESTROY and even WM_CLOSE messages to your message handler.
  • If the user simply clicks the X button of your app, obviously the above also applies.
  • If the user logs off or shuts down the PC, you'll receive WM_QUERYENDSESSION and WM_ENDSESSION messages.

For console apps, you can use the SetConsoleCtrlHandler function to be notified of most cases of app termination (I don't have any experience with this so can't give many details).

For services, you can use the RegisterServiceCtrlHandler function in much the same way.

For all types of apps, if the app is terminated forcibly by another process via the TerminateProcess function, there is no way to get notified :

If a process is terminated by TerminateProcess, all threads of the process are terminated immediately with no chance to run additional code. This means that the thread does not execute code in termination handler blocks. In addition, no attached DLLs are notified that the process is detaching.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM