For reasons I think are not relevant here I have one or more Threads that comunicate with a single instance UI (a Form).
In the worker threads I need to report progress or input data or simple choices. All of those come from user interaction with the UI and, of course, for M$ .NET, all the UI runs in the main thread.
Obviously I need to handle the thread synchronization across the UI (main) thread and the worker ones. I do it by properly verifying InvokeRequired and company.
There is a miriad of posts and articles around there discussing incoherences and subtleties in InvokeRequired, IsHandleCreated, IsDisposed and so on, so I won’t speak about it.
I just have to say that my UI, that is just a Form, was supposed to be shown as a modal or modeless form, depending on the caller wish.
One could just UI.Warn( "Warning!" ) while other could UI.Question( "Make a choice:", options... ).
Consider now the following excerpt from M$DN documentation:
Unlike non-modal forms, the Close method is not called by the .NET Framework when the user clicks the close form button…
I have never attended that a form shown as modal, nevertheless their implementors say it will not be destroyed, could fall in a non-usable state after closing (hiding).
But it does!
When the form returns from ShowDialog( ) its Handle is just trashed away in the belief that when it is needed again, ShowDialog( ) will be called and the handle will be recreated.
I have no idea why M$ stuff needed to do this way, but I just thought that I’d be able to have the very same form acting perfectly as modal or modeless without a problem. M$DN docs say nothing about it being forbidden (or I am too drunk to find it)!
Well, in the end it is a relativelly simple (and dirty) way to fix it.
var r = ShowDialog( );
// Handle thrown away aftr "ShowDialog()" supposing the
// next one will recreate it.
if ( !this.IsHandleCreated )
{
// Force "Handle" recreation here, while in the main thread,
// before any "Show()" happens.
CreateHandle( );
}
return r;
It works, but I wonder if it shouldn’t be any decent way to reach the same end.
(Maybe prgramming in something that does not carry any limitting ancestor compatibility baggage as .NET still does…)
Are you sure you don’t have this backward? I created a simple blank form to use as a modal dialog, and then tested it with a simple form that just has a button that shows the dialog.
I can show the dialog repeatedly with no trouble.
Now, if I call
theDialog.Show(), close it, and then try to show it again, I get aObjectDisposedException.So, the documentation is correct:
ShowDialogdoes not callForm.Close, whereasShowapparently does.EDIT:
The documentation for Form.Close tells you what you have to do if you want to prevent the form from being destroyed:
With that information and a few minutes’ thought, it’s trivial to have a form that you can show as modal or non-modal: