How to open a new window form within another form in c#

11,610

Solution 1

Try like this:

this.Hide();
Main.ShowDialog();
this.Close();

First, you hide the login form. Next, you show the Main form dialog, but prevent the caller of "ShowDialog()" from continuing until the dialog is closed. Last, once the dialog is closed, you close the login form, ending the application.

Solution 2

The application is still running because you still have one form that is still alive but hidden.

You can subscribe the Close event in MainForm and manually exit the application through Application.Exit().

Another option is to make sure there is only one window alive: open MainForm in the handler of the LoginForm.Close event as described here: Windows Forms: Change application mainwindow at runtime

MyForm1 f = new MyForm1();
f.Close += OnOpenOverviewWin();
Application.ShutdownMode = ShutdownMode.OnLastWindowClose;
Application.Run(f);

void OnOpenOverviewWin()
{
  if (loginok)
  {
    MyOverViewForm f = new MyOverViewForm ();
    f.Show();
  }
}
Share:
11,610
sanzy
Author by

sanzy

Updated on June 21, 2022

Comments

  • sanzy
    sanzy almost 2 years

    i have developed a windows form application using c#.

    it has 2 forms like login form and main form. When i enter the correct login credentials it should close(not hide) the login form and display the main form.

    i used the following code

    MainForm main=new MainForm();
    this.hide();//close login form
    main.show();//display main form
    

    but when I close the main form using the cross mark(right upper corner) in the mdi container, the main form closes but the application is still running in the task manager.

    If I use the following code instead of the previous code, application will close before main form display.

    this.close()//close login form
    main.show();//display main form
    

    do i have to hide mdi container from the main form or is there any way to achieve this? please help.