C#如何同时打开Form2和关闭Form1?

How to open Form2 and close Form1 in the same time by C#?

我在尝试从表单 1 打开表单 2 并关闭表单 1 时遇到问题,我已经尝试了这些解决方案,但找不到正确的解决方案: 解决方案一:-

Form2 form2 = new Form2();
            form2.Show();
            this.Close(); //close Form1

解决方案 2:- 在文件 Program.cs

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        MyApplicationContext context = new MyApplicationContext();
        Application.Run(context);
    }
    public class MyApplicationContext : ApplicationContext
    {
        private Form1 form1 = new Form1();

        public MyApplicationContext()
        {
            form1 = new Form1();
            form1.Show();
        }
    }

并在 Form1.cs

Form1 form1 = new Form1();
            form1.Show();
            this.Close();

此解决方案有效,但关闭应用程序后,我发现它仍在后台运行。

我该如何解决这个问题?

你可以试试这个代码:

       this.Hide();
        Form2 form2 = new Form2();
        form2.Closed += (s, args) => this.Close();
        form2.Show();