I have very simple WinForms application, which consists of three forms: Form1, Form2 and Form3. Form1 is the main application window. By hitting a button in this window user opens Form2 as a modal dialog through a call to ShowDialog(this)
. Similarly, Form2 has another button, which opens Form3 through another call to ShowDialog(this)
. In each case this
points to hosting from: Form1 and Form2 respectively.
It all works very fine until user hist OK button in Form3. At this moment both Form3 and Form2 modal windows close and user returns to Form1. Logically, user should return to Form2, from which he or she launched Form3. Why it happens? Thank you.
Form1 opens Form2 in the following code:
private void form1_ButtonClick(object sender, EventArgs e)
{
Form2 settings = new Form2();
DialogResult result = settings.ShowDialog(this);
if (result == DialogResult.OK)
{ }
}
Then Form2 opens Form3 in this code:
private void form2_ButtonClick(object sender, EventArgs e)
{
Form3 settings = new Form3();
DialogResult result = settings.ShowDialog(this);
if (result == DialogResult.OK)
{ }
}
Interestingly, debugger after exiting function form2_ButtonClick() immediately drops into form1_ButtonClick() as a next step. I inspected all calls of handlers and did not see any code associated with form closing. Even when I comment our all code of handlers forms still close in cascade.
I suspected that form closing is due to dialog result assigned to form buttons, so I disabled both and added explicit button handlers. Result remains the same. Also, I commented out all processing of dialog result in both functions. Still, closing Form3 magically closes also its parent Form2 and drops directly into Form1.
As advised, I ve also added explicit Form2.FormClosing() handler and put break-point there. Yes, this handler is called immediately on closing Form3 without any code suggesting this call.
Solution (partial)
Not being able to find reasons, I followed valuable advise by @Otterprinz and modified handler as follows.
private bool allowClose = true;
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if (!allowClose)
{
e.Cancel = true;
allowClose = true;
}
}
Before showing Form3 I assign allowClose = false
. It works and prevents Form2 from abrupt closing. Why this situation happens at all I dont know. The forms are not complex at all. I ve carefully inspected their source code and did not see any wrong. These are not first and not even 100th forms I ve designed. Never seen this effect before. But, at least I ve found the solution due to your valuable advises. Thank you all for comments!