title: How can I distinguish between UI Close and forced shutdown with Delphi
body: <p>If a user tries to Close the application, I would like to display a Close Query confirmation dialog. If the system shuts down or the task or process is being ended from the Task Manager, I just want to clean up and close.</p>
  
  <p>I tried this code:</p>
  
  <pre><code>private
  procedure WMEndSession(var Message: TWMEndSession); message WM_ENDSESSION;
  </code></pre>
  
  <p>...</p>
  
  <pre><code>procedure TxxxForm.WMEndSession(var Message: TWMEndSession);
  begin
    gShuttingDown := Message.EndSession;
  end;
  </code></pre>
  
  <p>...</p>
  
  <pre><code>procedure TxxxForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
  begin
    Application.ProcessMessages;
    if gShuttingDown then
      CanClose := True
    else
      CanClose := MessageDlg('Are you sure you want to stop the close?', mtConfirmation,
         [mbYes, mbNO], 0) = mrYes;
  end;
  </code></pre>
  
  <p>The popup confirmation is showing whether I close the program or terminate the process from the Task Manager.</p>