No, it is not possible to hook the operating system’s decision to end a process. Note, this is not done by task manger, ending a process is the responsibility of the kernel.
You will need to do two things here:
- Connect event handlers to the normal user interface messages that tell a application to exit. Use these events to persist data, free resources, and otherwise exit cleanly.
- Handle exceptions as appropriate to catch errors and clean up and save data if possible.
Here are a three links to Raymond’s blog explaining why you cannot do what you are asking.
- Why can’t you trap TerminateProcess?
- Why do some process stay in Task Manager after they’ve been killed?
- The arms race between programs and users
Also, I addressed a similar StackOverflow question here.