How do I handle Ctrl+C in a Delphi console application?
console, delphi
Solution
From Windows API (MSDN):
BOOL WINAPI SetConsoleCtrlHandler(
PHANDLER_ROUTINE HandlerRoutine, // address of handler function
BOOL Add // handler to add or remove
);
A HandlerRoutine function is a function that a console process specifies to handle control signals received by the process. The function can have any name.
BOOL WINAPI HandlerRoutine(
DWORD dwCtrlType // control signal type
);
In the Delphi the handler routine should be like:
function console_handler( dwCtrlType: DWORD ): BOOL; stdcall;
begin
// Avoid terminating with Ctrl+C
if ( CTRL_C_EVENT = dwCtrlType ) then
result := TRUE
else
result := FALSE;
end;
Problem
Are there best practices and code snippets available which show how I can handle Ctrl+C in a Delphi console application? I have found some articles which give some information about possible problems with the debugger, with exception handling, unloading of DLLs, closing of stdin, and finalization for example this CodeGear forums thread.