Home > front end >  Difference in using Modal and Non-Modal forms
Difference in using Modal and Non-Modal forms

Time:09-17

I've a question regarding the using statement with Modal and Non-Modal Forms. What I want to accomplish is the same behaviour when I'm using the using statement. Below a example which works perfectly with Modal forms.

Dictionary<string, string> input;
using (var window = new Form1()
{
    window.ShowDialog();

    if (window.DialogResult == DialogResult.Cancel)
    {
        return Result.Cancelled;
    }

    input = window.GetInformation();
}

When I change the ShowDialog() to Show() the whole form doesn't work anymore. I've tried without the using statement but then I can't get information from my from like above. Is there a way to archieve the exact same result but with form.Show() instead of ShowDialog()?

Edit: When I show the form from an external application with ShowDialog() it isn't deactivated when the external application is clicked. But I'm using the OnDeactivated event which doesn't trigger in this situation. So I tried with Show() and this seems to work.

CodePudding user response:

If the question is why does the Show() not work when inside a Using statement, it is because Show() is non-modal and so program flow continues (i.e. doesn't wait for Form to close as ShowDialog() would). So flow continues to exit the Using, which disposes of objects created inside the Using, including the Form you have created. That's why it appears not to work.

Here's what I do to work around this issue.

I declare the Form I want to Show global to the class you are using:

private Form1 window;

and in the Function where I want to Show it:

if (window != null && !window.IsDisposed) window.BringToFront();
else
{
   var window = new Form1();
   window.Show();
   // ... rest of your code here
}

Of course if you aren't using ShowDialog() you have to capture the result a different way. The way I prefer for this is to use the FormClosing event

add this when you instantiate the form:

 window.FormClosing  = window_FormClosing;

then add whatever code you want to capture the result in the event handler:

    private void window_FormClosing(object sender, FormClosingEventArgs e)
    {
        Form1 window = sender as Form1;
        // Your code here
    }
  • Related