且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Delphi控制台应用程序中如何处理Ctrl + C?

更新时间:2023-02-19 20:04:56

从Windows API( MSDN ):

  BOOL WINAPI SetConsoleCtrlHandler(
PHANDLER_ROUTINE HandlerRoutine,//处理函数的地址
BOOL添加//处理程序以添加或删除
);

HandlerRoutine函数是控制台进程指定的用于处理进程接收到的控制信号的函数。该函数可以有任何名称。

  BOOL WINAPI HandlerRoutine(
DWORD dwCtrlType //控制信号类型
);






在Delphi中,处理程序例程应该是:

  function console_handler(dwCtrlType:DWORD):BOOL;标准
begin
//避免使用Ctrl + C
终止(如果(CTRL_C_EVENT = dwCtrlType))
result:= TRUE
else
result:= FALSE;
结束


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.

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;