views:

920

answers:

1

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.

+9  A: 

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;
Nick D
Ok, this shows how I can disable Ctrl+C - I should clarify my question: how do I perform a clean application shutdown after detecting Ctrl+C?
mjustin
Oh, I see. If you trap the Ctrl+C, like my example, you can set a sort of 'flag' and terminate *normally* whenever you want.
Nick D
I just remembered the "break := false;" that I used to put in my Turbo Pascal programs to disable Ctrl-Break. Ah, nostalgia...
Nick D
On very important thing to remember is that HandlerRoutine runs in a SEPARATE THREAD. If you don't start any other threads yourself, set the IsMultithread global variable to True so that any memory operations you perform will be safe.
Rob Kennedy
Also important is the calling convention. The callback function must use the stdcall calling convention or else your program will crash mysteriously.
Rob Kennedy
Thanks Rob, I forgot it. From now on it's a wiki, to further improve it.
Nick D