Differentiate between a Windows shutdown and a user's close request (Views: 100)


How can I differentiate between a Windows shutdown and a user's close request (Alt + F4 / titlebar close icon / file menu + close item / etc.) so that I can bypass the OnCloseQuery logic during a shutdown?


Windows sends a WM_QUERYENDSESSION message to the main window of your application. The default processing for that invokes your CloseQuery method, which (in your logged out case) replies "No". So you need to watch for the WM_QUERYENDSESSION message and set a flag for your CloseQuery method. Give the form a flag and method like so:

FShuttingDown: Boolean;

procedure WMQueryEndSession(var Msg: TMessage); message WM_QUERYENDSESSION;

procedure TForm1.WMQueryEndSession(var Msg: TMessage);
  {Tell CloseQuery it's a shutdown operation}
  FShuttingDown := True;
  {Let the default stuff happen to see if we can otherwise close}

Then in your CloseQuery event handler do:

if FShuttingDown then
  CanClose := True
  CanCLose := {User if "logged in"};

It is possible for the shutdown to be aborted by another application, however. So you need to watch for the WM_ENDSESSION message that gets sent telling you if you really are going to shut down:

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

procedure TForm1.WMEndSession(var Msg: TMessage);
  {Clear the flag if the shutdown was aborted}
  FShuttingDown := Msg.WParam <> 0;

<< Back to main page