1. Home
  2. Computing & Technology
  3. Delphi Programming

Detecting and preventing Windows shut down

By Zarko Gajic, About.com

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

~~~~~~~~~~~~~~~~~~~~~~~~~
procedure WMQueryEndSession
           (var Msg : TWMQueryEndSession) ;
           message WM_QueryEndSession;
~~~~~~~~~~~~~~~~~~~~~~~~~

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

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

To detect Windows Shutdown, we must trap the WM_EndSession message. Declare a message handling procedure in your main Form'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) ;
begin
if Msg.EndSession = TRUE then
   ShowMessage('Windows is shutting down ' + #10#13
               + 'at ' + FormatDateTime('c', Now)) ;
   inherited;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» Overwrite in TMemo and TEdit - Clear All Edit Controls on a Form
« ListBox with a horizontal scroll bar

Zarko Gajic
Guide since 1998

Zarko Gajic
Delphi Programming Guide

Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. 2000 Delphi Tips
  7. Detecting and preventing Windows shut down

©2009 About.com, a part of The New York Times Company.

All rights reserved.