How to handle Win32 Application termination

2019-07-23 18:35发布

问题:

I have an Win32 application with no window written in C. My question is: is there any way to handle the termination of my application. Ex. closing it from the task manager or via the console.

回答1:

It is unclear from the question, but if this is a console mode application then you can call SetConsoleCtrlHandler to install a callback that Windows will call just before it terminates your app. Beware that this callback runs on a separate thread and that you have to complete the callback function quickly.

If it is a native Windows program that just doesn't create a window then you really do need a window to get notifications like this. Which is not a problem, it doesn't have to be visible. Just don't call ShowWindow().

Note that atexit() as mentioned will not work, these are rude aborts you are talking about that don't let the program go through its normal shutdown sequence.



回答2:

You might like to take a look at the atexit() function (http://msdn.microsoft.com/en-us/library/tze57ck3%28v=vs.100%29.aspx).

Using this function you can install handlers which are called when the program terminates.



标签: c winapi signals