Author: William Gerbert
How to preventing a user from closing a window except at shutdown or restart
Answer:
We all know how to prevent a window from closing: Simply write event code for the 
OnCloseQuery event and set CanClose to False. Once that's done, no matter what a 
user presses, the window won't close. Here's some code:
1   
2   procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
3   begin
4     CanClose := False;
5   end;
But what if you wanted to be able to close a window only when you reboot the 
machine? With the scenario above, that would be impossible. Fortunately though, 
there is a solution, and it resides in the windows message WM_QUERYENDSESSION.
WM_QUERYENDSESSION is generated by Windows when the OS is resetting: Either at a 
shutdown or a restart. Using this message, we can set a boolean flag variable and 
interrogate its value in OnCloseQuery to allow us to close the window and reset the 
operating system. Look at the unit code below:
6   unit Unit1;
7   
8   interface
9   
10  uses
11    Windows, Messages, SysUtils, Classes,
12    Graphics, Controls, Forms, Dialogs;
13  
14  type
15    TForm1 = class(TForm)
16      procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
17    private
18      procedure WMQueryEndSession(var message: TWMQueryEndSession);
19        message WM_QUERYENDSESSION;
20    public
21      WindowsClosing: Boolean;
22    end;
23  
24  var
25    Form1: TForm1;
26  
27  implementation
28  
29  {$R *.DFM}
30  
31  { TForm1 }
32  
33  procedure TForm1.FormCreate(Sender: TObject);
34  begin
35    WindowsClosing := False;
36  end;
37  
38  procedure TForm1.WMQueryEndSession(var message: TWMQUERYENDSESSION);
39  begin
40    WindowsClosing := True;
41  end;
42  
43  procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
44  begin
45    CanClose := WindowsClosing;
46  end;
47  
48  end.
As you can see, I've created a public variable called WindowsClosing. When WM_QUERYENDSESSION fires, it sets the variable to True. Then in OnCloseQuery, CanClose is set to the value of WindowsClosing. Notice that I set WindowsClosing to False in OnCreate. This is purely for initialization purposes to make sure that previous attempts to close the window are foiled.
			
           |