Notice Of Closure

Please note that this website is due to close down on 15th June 2020.

In the interim I will try to move as much content as possible over to my GitHub account. Thanks to everyone who has supported the site over the years.

» Help

How to detect and prevent Windows shut down


When Windows is about to shut down, it sends a WM_QUERYENDSESSION message to all open applications. To detect (and prevent shutdown), we must define a message handler for this message. Put this definition in the private section of the main form:

procedure WMQueryEndSession(var Msg: TWMQueryEndSession);

Also, to prevent Windows shutting down put this method in the implementation section of the unit:

procedure TForm1.WMQueryEndSession(var Msg: TWMQueryEndSession);
  if MessageDlg('Close Windows ?', mtConfirmation, [mbYes,mbNo], 0) = mrNo then
    Msg.Result := 0
    Msg.Result := 1 ;

To detect Windows Shutdown, we must trap the WM_ENDSESSION message. Declare a message handling procedure in your main frm's private section:

procedure WMEndSession(var Msg: TWMEndSession); message WM_ENDSESSION;

Also, add the following procedure to the implementation section of your unit:

procedure TForm1.WMEndSession(var Msg: TWMEndSession);
  if Msg.EndSession = True then
      'Windows is shutting down ' + #10#13 + 'at ' + FormatDateTime('c', Now)
Author: Unknown
Contributor: Riccardo Faiella (Topellina)
Added: 2012-07-06
Last updated: 2012-07-06

« Return to contents »