When Windows are being shutdown or restarted, all runnig applications are closed of course. This can be dangerous, because you can lost your unsaved documents. But there is an easy way to detect, that Windows wants to shutdown and your application can do everything necessary to close properly.This “trick” is pretty simple. When you shutdown or restart system, Windows sends the WM_QUERYENDSESSION message to all running applications. Standard Delphi form has an OnCloseQuery event, that detects this message. In this procedure, you can let Windows close your application or try to deny it.
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if MessageDlg('Are you sure you want to quit?', mtConfirmation, mbYesNoCancel, 0) = mrYes then CanClose := true else CanClose := false; end;
When you set the CanClose parameter to true, you are allowing Windows to shutdown, set it to false to try to disallow it. But remember “who is the master”. Windows can force your application to close even if you try to stop it.