In this WinForms project, I have a certain information form (InfoForm) which pops up for 2 seconds, then disappears. The way I do this is by calling
infoForm.Show();
and then inside InfoForm I have a Timer that ticks after 2 seconds and calls Close().
Now, sometimes there’s another form ErrorForm I need to show modally (using errorForm.ShowDialog()), to inform the user that an error has occurred, and they need to click OK before they can continue. This can happen while the InfoForm is opening and closing, and the one should not affect the other.
But it does.
I have gone so far as to put a breakpoint on the call to ShowDialog, and if the InfoForm is open at the time that I hit the breakpoint, then when I click ‘Step Over’, instead of popping up the ErrorForm and waiting for me to click "OK", the debugger just steps over the line and is already on the next line, as if the form never opened. Meanwhile in the background the InfoForm has closed, so if I reset the execution point to the call to ErrorForm.ShowDialog(), and then "Step Over", the form appears, as expected, and waits for me to click "OK" before moving to the next statement.
Removing breakpoints and writing to a debug log confirms my suspicion that it’s the closing of the InfoForm that is causing my ErrorForm to be untimely closed:
Thread 09 – 2011/12/14 16:39:30.574 – Info form shown
Thread 09 – 2011/12/14 16:39:31.300 – Before ErrorForm.ShowDialog
Thread 09 – 2011/12/14 16:39:32.584 – Timer Tick
Thread 09 – 2011/12/14 16:39:32.585 – Info form closing
Thread 09 – 2011/12/14 16:39:32.593 – Error form closing
Thread 09 – 2011/12/14 16:39:32.593 – After ErrorForm.ShowDialog
Why is this happening, and what is the cure?
You should pass the
MainFormas owner toErrorForm.ShowDialog().