Modal forms do exactly what βmodalβ means; they turn off all other windows in the application. This is very important, your program is in a somewhat dangerous state. You have a piece of code waiting for the dialog to close. Indeed, bad things can happen if these other windows have not been disabled. Just as the user can start the modal dialog again, now your code is nested twice. Or she can close the dialog box owner window, now it suddenly disappears.
These are the exact problems you encountered if you call Application.DoEvents () inside the loop. This is one way to make the form behave modally without disabling other windows. For example:
Form2 mDialog; private void button1_Click(object sender, EventArgs e) { mDialog = new Form2(); mDialog.FormClosed += (o, ea) => mDialog = null; mDialog.Show(this); while (mDialog != null) Application.DoEvents(); }
This is dangerous.
Of course, it is better to use modal forms in the way they were designed so as not to disturb. If you do not need a modal form, just do not make it modal, use the Show () method. Subscribe to the FormClosing event to find out what it is about to close:
private void button1_Click(object sender, EventArgs e) { var frm = new Form2(); frm.FormClosing += new FormClosingEventHandler(frm_FormClosing); frm.Show(); } void frm_FormClosing(object sender, FormClosingEventArgs e) { var frm = sender as Form2;
Hans passant
source share