Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a console window program be notified when its close button is clicked?

Tags:

winapi

delphi

Does the Windows API provide a way to notify a running Delphi application in a console window when the user terminates it with a click on the close button (instead of using Ctrl+C)?

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

like image 219
mjn Avatar asked Dec 22 '22 03:12

mjn


1 Answers

The OS notifies console programs of various events via "control signals." Call SetConsoleCtrlHandler to configure a function for the OS to call to deliver signals. The signal for a closed window is CTRL_CLOSE_EVENT.

function ConsoleEventProc(CtrlType: DWORD): BOOL; stdcall;
begin

  if (CtrlType = CTRL_CLOSE_EVENT) then
  begin
    // optionally run own code here
    // ...

  end;

  Result := True; 
end;

...

begin
  SetConsoleCtrlHandler(@ConsoleEventProc, True);
  // my application code here
  // ...
end.
like image 55
mjn Avatar answered Dec 24 '22 00:12

mjn