Hello. In the class of the child form, the FormClosing event is defined, in which data from the form is saved to some file before closing.

if (this.Text.Contains("txt")) { string path= @"D:\SaveFiles\"+this.Text+".txt"; File.WriteAllLines(path, textBox1.Lines); } else { SaveAs sva = new SaveAs(); sva.ShowDialog(); string path=@"D:\SaveFiles\" + sva.textBox1.Text + ".txt"; File.WriteAllLines(path, textBox1.Lines); } 

With the closure of the child form, everything is fine. But when you try to close a framing form, you must first close all child forms (the FormClosing event of the child forms is called), how to fix it so that you can close the entire application at once. Help me please.

    1 answer 1

    If I understood correctly, when you close the child form, you see if the previously typed text was saved to a file, and if so, silently save the changes to this file and close the form.

    If the text was typed in the child MDI form, but was not saved to the file, then suggest that you do this and call the save dialog.

    When you close the main form, you work out this mechanism for each of the open child MDI forms and the save changes dialog appears for each of the child forms, where the text was not saved.

    So, in general, you have the right approach from the user's point of view, as it would be a shame if when you close the application, the changes to the text in the MDI forms would simply disappear.

    I can recommend to do the following: in the parent form, create an additional public property public bool SaveChangesFromMDI {get; set;} public bool SaveChangesFromMDI {get; set;} . When initializing the main form, set this property to True , or, if you have C # 6.0 and VS 2015, you can immediately do this: public bool SaveChangesFromMDI { get; set; } = true; public bool SaveChangesFromMDI { get; set; } = true;

    Next, add the following code to the FormClosing handler of the main form:

      private void FormMain_FormClosing(object sender, FormClosingEventArgs e) { if (SaveChangesFromMDI) { //Пробежимся по всем MDI формам и посмотрим, а есть ли там что сохранять? bool ShowSaveQuery = false; for (int x = 0; x < this.MdiChildren.Length; x++) { if (!((Form)this.MdiChildren[x]).Text.Contains(".txt")) { //В какой-то из форм нашелся не сохраненный текст, тогда установим флаг, //что нам нужно показать запрос на сохранение данных ShowSaveQuery = true; break; } } DialogResult dr = DialogResult.None; //Если нужно показать запрос, то показываем его, что бы потом проанализировать решение пользователя if (ShowSaveQuery) { dr = MessageBox.Show("Имеются несохраненные данные в открытых документах. Сохранять эти данные?", "Выход", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); } //Смотрим, что же выбрал пользователь, да и выбрал ли? switch (dr) { case DialogResult.Yes: //Пользователь хочет сохранять данные SaveChangesFromMDI = true; break; case DialogResult.None: case DialogResult.No: //Не нужно сохранять данные SaveChangesFromMDI = false; break; case DialogResult.Cancel: //Пользователь передумал завершать работу, отменяем закрытие приложения. e.Cancel = true; break; } //А теперь в цикле мы можем принудительно позакрывать дочерние формы: for (int x = 0; x < this.MdiChildren.Length; x++) { ((Form)this.MdiChildren[x]).Close(); } } } 

    But in order for the child forms to know what to do, based on the choice of the user, then the code of their FormClosing event FormClosing needs to be slightly supplemented, for example:

      ... if (MainForm.SaveChangesFromMDI) { if (this.Text.Contains("txt")) { string path = @"D:\SaveFiles\" + this.Text + ".txt"; File.WriteAllLines(path, textBox1.Lines); } else { SaveAs sva = new SaveAs(); sva.ShowDialog(); string path = @"D:\SaveFiles\" + sva.textBox1.Text + ".txt"; File.WriteAllLines(path, textBox1.Lines); } } 

    Those. from the child MDI form, we look at the parent, at the value of the SaveChangesFromMDI property, and if it is true , then we call your save mechanism, and if the user decides not to save anything, then it will be false and nothing will be saved, no save dialogs will be shown.

    You can make a slightly different logic, of course, this is more convenient for you.


    Another option to exit the application will be to call Environment.FailFast(null) , but this will work, but the method is not correct, because This is crash in effect.

    And you can also see the answers to this question about the completion of the application.