win32api.SetConsoleCtrlHandler

SetConsoleCtrlHandler(ctrlHandler, bAdd)

Adds or removes an application-defined HandlerRoutine function from the list of handler functions for the calling process.

Parameters

ctrlHandler : callable

The function to call. This function should accept one param - the type of signal.

bAdd : int

True if the handler is being added, false if removed.

Comments

Note that the implementation is a single CtrlHandler in C, which keeps a list of the handlers added by this function. So although this function uses the same semantics as the Win32 function (ie, last registered first called, and first to return True stops the calls) the true order of all Python and C implemented CtrlHandlers may not match what would happen if all were implemented in C.
This handler must acquire the Python lock before it can call any of the registered handlers. This means the handler may not be called until the current Python thread yields the lock.
A console process can use the win32api::GenerateConsoleCtrlEvent function to send a CTRL+C or CTRL+BREAK signal to a console process group.
The system generates CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, and CTRL_SHUTDOWN_EVENT signals when the user closes the console, logs off, or shuts down the system so that the process has an opportunity to clean up before termination.

Win32 API References

Search for SetConsoleCtrlHandler at msdn, google or google groups.