How to detect if my Windows application has ended?

645 views Asked by At

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

2

There are 2 answers

3
Kirill Kobelev On

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.

0
user1610015 On

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.