When ending a process in the task manager, how can I make my program continue to execute a section of code before closing?

I have used “SIGTERM”, “CreateEvent WaitForSingleObject”, “job object”, “heartbeat” and other methods before after, but none of them gave me the result I wanted. When I end the process from the task manager, the program closes without executing any code.
So, does anyone any effective methods

You can’t really: https://stackoverflow.com/questions/1527450/can-i-handle-the-killing-of-my-windows-process-through-the-task-manager

Have you tried using a context manager (a with statement) with a custom class implementing your callback code in __exit__ ?