2

I am trying to show a form using Form.ShowDialog as shown below:

var f = new Form();
if(f.ShowDialog() == DialogResult.OK)
{
     ...
}
...
if(f.ShowDialog() == DialogResult.OK)
{
     ...
}

The issue is the OnHandleDestroyed is called once a dialog result is returned and the form is closed.

  • Why do I care about OnHandleDestroyed? I have an OpenGL control on the form, and it disposes the Context when OnHandleDestroyed is called.
  • Why don't I dispose of the form, and use ShowDialog on the new form? I am trying to reuse the form as loading the form is slow - but populating it with data is quick.

So the question is: Is it possible to use ShowDialog() without closing the form (and hiding it instead) OR to show a form modally using Show() and Hide()?

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
MineR
  • 2,144
  • 12
  • 18
  • You could write your own logic to hide the form is input is given – EpicKip Oct 16 '17 at 11:55
  • But how do I keep it modal? – MineR Oct 16 '17 at 11:56
  • Possible duplicate of [Hide form instead of closing when close button clicked](https://stackoverflow.com/questions/2021681/hide-form-instead-of-closing-when-close-button-clicked) – Sinatr Oct 16 '17 at 11:58
  • @Sinatr, it's not a duplicate of that one because I specifically want the form to be Modal. – MineR Oct 16 '17 at 11:59
  • 1
    Don't close it then. You have to choose: either recreate opengl stuff every time or .. don't close the form. There are the ways to make modeless form modal, look e.g. [here](https://stackoverflow.com/a/8567719/1997232). – Sinatr Oct 16 '17 at 12:00
  • @Sinatr - Sorry, I mean that I want it to be modal when it is shown (no other form other than its children can receive input). Once hidden, it is no longer modal. – MineR Oct 16 '17 at 12:03
  • That may work. Let me give that a go. – MineR Oct 16 '17 at 12:07
  • Pay close attention to the comments in that linked answer. That solution requires the use of `DoEvents` and that is a known bad practice, because it is very hard to use without nasty side-effects. – DonBoitnott Oct 16 '17 at 12:09

1 Answers1

4

When you show a form using ShowDialog, after closing the form DestroyHandle will be called automatically.

To prevent the behavior you can override DestroyHandle method and write your own logic.

Example

public class MyForm : Form
{
    protected override void DestroyHandle()
    {
        if (!Modal || Disposing)
            base.DestroyHandle();
    }
}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • Also don't forget to dispose your modal dialogs when you don't need them anymore. For more information take a look at [this post](https://stackoverflow.com/a/39501121/3110834). – Reza Aghaei Oct 16 '17 at 12:19
  • Works great Reza! Solves my exact problem. – MineR Oct 16 '17 at 12:28