Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle Ctrl+C in a Delphi console application?

Tags:

console

delphi

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.

like image 368
mjn Avatar asked Jun 16 '09 08:06

mjn


1 Answers

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;
like image 122
user1000368 Avatar answered Oct 26 '22 13:10

user1000368