C# Opening a new form and closing the other one

前端 未结 5 500
深忆病人
深忆病人 2021-01-12 07:03

In my program I show a login form before the main form, once the program detects a successful login I use this:

MainForm Main = new MainForm();
Main.Show();
         


        
5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-12 07:44

    You can use ApplicationContext.MainForm to specify current main form for the application:

    static class Program
    {
        public static ApplicationContext Context { get; set; }
    
        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
    
            Context = new ApplicationContext(new LoginForm());
            // pass Context instead of just new LoginForm()
            Application.Run(Context);
        }
    }
    

    then in in login handler:

    private void login_Click(object sender, EventArgs e)
    {
        Program.Context.MainForm = new MainForm();
    
        // close login form
        this.Close();
    
        // set up context to track main form instead of login
        Program.Context.MainForm.Show(); 
    }
    

提交回复
热议问题