0

I am trying to do the same thing as is described in the following thread (in a C# winforms app):

How to open a new independent form?

And is answered with this: https://stackoverflow.com/a/14902079/5342320

The problem is I can't find this setting in Visual Studio Community 2015.

The only Microsoft documentation I find for this is the following:

https://msdn.microsoft.com/en-us/library/vstudio/0hzfysdc(v=vs.100).aspx

So it appears this only exists in VB projects. I found the setting when I created a VB winforms project. Is there a way to do something similar in a C# project?

As a workaround I've used a modal form instead:

frmMyForm frm = new frmMyForm();
frm.ShowDialog();

But this makes it so that I can't close the parent form before the new form has been closed. What I want is to be able to close the parent form after opening the new form, without closing the whole application.

Community
  • 1
  • 1
Pikabanga
  • 45
  • 7

1 Answers1

0

By default your Main method contains the following line

Application.Run(new YourMainForm());

Just change it to

new YourMainForm().Show();
Application.Run();

EDIT: It turns out that it's not so simple, because now the application never exits. But the idea is the same. Although it seems that there is similar answered question, I don't like the answer and would rather have this class in my pocket (library)

public class LastFormClosingApplicationContext : ApplicationContext
{
    public LastFormClosingApplicationContext(Form mainForm) : base(mainForm) { }
    protected override void OnMainFormClosed(object sender, EventArgs e)
    {
        for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
        {
            var form = Application.OpenForms[i];
            if (form != MainForm)
            {
                MainForm = form;
                return;
            }
        }
        base.OnMainFormClosed(sender, e);
    }
}

and anytime I need something like this, would just replace

Application.Run(new YourMainForm());

with

Application.Run(new LastFormClosingApplicationContext(new YourMainForm()));
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343