How do I prevent the app from terminating when I close the startup form?

后端 未结 4 826
一个人的身影
一个人的身影 2020-11-22 05:13

There is two Forms in my project : Form1 and Form2. There is a button in Form1, and what I want to do is closing Form1 and showing Form2 when that button clicked.

Fi

4条回答
  •  -上瘾入骨i
    2020-11-22 05:24

    By default, the first form controls the lifetime of a Windows Forms application. If you want several independent windows forms your application context should be a separate context from the forms.

    public class MyContext : ApplicationContext
    {
       private List
    forms; private static MyContext context = new MyContext(); private MyContext() { forms = new List(); ShowForm1(); } public static void ShowForm1() { Form form1 = new Form1(); context.AddForm(form1); form1.Show(); } private void AddForm(Form f) { f.Closed += FormClosed; forms.Add(f); } private void FormClosed(object sender, EventArgs e) { Form f = sender as Form; if (form != null) forms.Remove(f); if (forms.Count == 0) Application.Exit(); } }

    To use the context, pass it to Application.Run (instead of the form). If you want to create another Form1, call MyContext.ShowForm1() etc.

    public class Program
    {
       public void Main()
       {
          Application.Run(new MyContext());
       }
    }
    

提交回复
热议问题