I'm writing a Windows console program that takes no console input. The user closes it by clicking the close button. Is there any way to recognize that it's being closed to perform one last action?
Yes, there is. You set a console contrl handler function (a callback) which gets informed about a few events. Here's an example in Delphi. You should get the idea if you need it for another language.
function MyConsoleEventHandler( dwCtrlType : DWORD) : BOOL; stdcall;
// note: will be called from another thread!
begin
result := TRUE;
try
case dwCtrlType of
CTRL_C_EVENT : Writeln('Ctrl+C');
CTRL_BREAK_EVENT : Writeln('Ctrl+Break');
CTRL_CLOSE_EVENT : Writeln('CloseTask-Signal');
CTRL_LOGOFF_EVENT : Writeln('LogOff-Signal');
CTRL_SHUTDOWN_EVENT : Writeln('Shutdown-Signal');
else
Writeln('Console-Event ',dwCtrlType,' received');
end;
if g_StopServer <> nil then begin
Writeln( 'Stopping the Server ...');
g_StopServer.SetEvent;
end;
except
// catch all
end;
end;
class procedure TMyServer.Run;
begin
SetConsoleCtrlHandler( @MyConsoleEventHandler, TRUE);
Writeln('Server listening at port '+IntToStr(PORT_SOAP));
Writeln('Press Ctrl+C to stop the server.');
Writeln;
g_StopServer.WaitFor( INFINITE);
end;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.