How is Ctrl-C message delivered to a process running on windows?
When Windows needs to notify a console program of an external event, there is no window message loop to send the notification to, so Windows will create a thread in the target process to execute whatever callback function is defined. The default handler for the CTRL+C event just calls ExitProcess
, but hooking the CancelKeyPress
event calls the Win32 SetConsoleCtrlHandler
function with a handler function.
The documentation for the handler function explains how it works:
An application-defined function used with the SetConsoleCtrlHandler function. A console process uses this function to handle control signals received by the process. When the signal is received, the system creates a new thread in the process to execute the function.
Note that the thread that Windows injects into your process has a fairly small stack, so the CLR handler routine actually queues up a Threadpool work item to execute your event handler. This means that the thread injected by Windows and a worker thread could both be created, causing you to see up to 2 additional threads during the processing of the CTRL+C event.
Yes, Windows starts up a thread to call the handler that's registered by SetConsoleCtrlHandler(). Which is called by the Hook() method of a little internal helper class named ControlCHooker. Which is called by the add() accessor of the Cancel.CancelKeyPress event. The Windows callback makes your event handler run.
A good disassembler like Reflector or ILSpy as well as the Reference Source can help you discover these implementation details.