1

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136

1 Answers1

1

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;
JensG
  • 13,148
  • 4
  • 45
  • 55
  • Note that the `CTRL_CLOSE_EVENT` that you get when the console window's close button is clicked appears to be advisory: returning `TRUE` will not stop the process from being terminated. Be quick about what you need to do. For some details, see [this question where someone asks whether they can stop the console window from being closed](http://stackoverflow.com/questions/20232685/win32-c-opening-the-console-from-the-api/). – chwarr Dec 07 '13 at 07:16