Delphi: close all forms (except MainForm), but ignore any OnCloseQuery dialogs

Basically, I use the TTimer event to close all open forms and return the user to the main form. I could iterate through Screen.Forms :

 for i := 0 to Screen.Formcount - 1 do Screen.Forms[i].close; 

The problem is OnCloseQuery events in some of these forms - they exit MessageDlg , which interrupt this process OnCloseQuery

+4
source share
2 answers

You can use the flag in your main form, which your other forms would check before asking the user whether to continue or not. Something like that:

block1

 type TForm1 = class(TForm) .. public UnconditinalClose: Boolean; end; .. procedure TForm1.Timer1Timer(Sender: TObject); begin UnconditinalClose := True; end; 

unit 2:

 implementation uses unit1; procedure TForm2.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := unit1.Form1.UnconditinalClose; if not CanClose then // ask the user if he/she sure he/she wants to close end; 


Another solution might be to remove OnCloseQuery event handlers of other forms. This would be practical only if these other forms were released (released) upon closing and not hidden (edited to reflect Rob's comment):

 procedure TForm1.Timer1Timer(Sender: TObject); var i: Integer; SaveHandler: TCloseQueryEvent; begin for i := 0 to Screen.Formcount - 1 do if Screen.Forms[i] <> Self then begin SaveHandler := Screen.Forms[i].OnCloseQuery; Screen.Forms[i].OnCloseQuery := nil; Screen.Forms[i].Close; Screen.Forms[i].OnCloseQuery := SaveHandler; end; end; 
+7
source
 for i := 1 to Screen.Formcount - 1 do Screen.Forms[i].close; 

Enter i with 1, not 0.

-1
source

Source: https://habr.com/ru/post/1415822/


All Articles