Hi Bardakargor,
There really is nothing you can do if your process is killed. By definition, killing a process is just that - killing it. The process does not get an opportunity to run any code. This is very much "by design".
Imagine that you could register a routine that was called when your process was killed by the user (or by another process). What would it do? All the other threads in your process would be in an indeterminate state, How would you synchronize with them? Remember, the idea is that the process needs to be killed.
The other scenario is even tougher: your code is benign and trying to do the right thing - e.g. clean up and be a good system citizen. Some code isn't. Imagine what a boon to a malware author it would be if the OS allowed code to be run for a process that was being killed. It would be bad enough for malicious processes that were running with standard user privileges, and completely awful for any running with administrative privileges.
Critical finalizes and structured exception handling will not solve this fundamental issue.
ON the upside, the OS will free all the resources it knows about when your process is killed, namely memory and kernel objects. Those will not leak. But explorer doesn't know about your process so it cannot clean up for it.
One way to solve this would be to have a monitoring process that keeps track of your other processes state and cleans up for it. You could do this with a simple process, or with a service. You might also consider some kind of shell extension that had its own thread that did the same thing.
Best Regards
RGR