c# open a new form then close the current form?

C#WinformsForms

C# Problem Overview


For example, Assume that I'm in form 1 then I want:

  1. Open form 2( from a button in form 1)
  2. Close form 1
  3. Focus on form 2

C# Solutions


Solution 1 - C#

Steve's solution does not work. When calling this.Close(), current form is disposed together with form2. Therefore you need to hide it and set form2.Closed event to call this.Close().

private void OnButton1Click(object sender, EventArgs e)
{
    this.Hide();
    var form2 = new Form2();
    form2.Closed += (s, args) => this.Close(); 
    form2.Show();
}

Solution 2 - C#

Many different ways have already been described by the other answers. However, many of them either involved ShowDialog() or that form1 stay open but hidden. The best and most intuitive way in my opinion is to simply close form1 and then create form2 from an outside location (i.e. not from within either of those forms). In the case where form1 was created in Main, form2 can simply be created using Application.Run just like form1 before. Here's an example scenario:

I need the user to enter their credentials in order for me to authenticate them somehow. Afterwards, if authentication was successful, I want to show the main application to the user. In order to accomplish this, I'm using two forms: LogingForm and MainForm. The LoginForm has a flag that determines whether authentication was successful or not. This flag is then used to decide whether to create the MainForm instance or not. Neither of these forms need to know about the other and both forms can be opened and closed gracefully. Here's the code for this:

class LoginForm : Form
{
    public bool UserSuccessfullyAuthenticated { get; private set; }

    void LoginButton_Click(object s, EventArgs e)
    {
        if(AuthenticateUser(/* ... */))
        {
            UserSuccessfullyAuthenticated = true;
            Close();
        }
    }
}

static class Program
{
    [STAThread]
    static void Main()
    {
        LoginForm loginForm = new LoginForm();
        Application.Run(loginForm);

        if(loginForm.UserSuccessfullyAuthenticated)
        {
            // MainForm is defined elsewhere
            Application.Run(new MainForm());
        }
    }
}

Solution 3 - C#

Try to do this...

{
    this.Hide();
    Form1 sistema = new Form1();
    sistema.ShowDialog();
    this.Close();
}

Solution 4 - C#

The problem beings with that line:

Application.Run(new Form1()); Which probably can be found in your program.cs file.

This line indicates that form1 is to handle the messages loop - in other words form1 is responsible to keep executing your application - the application will be closed when form1 is closed.

There are several ways to handle this, but all of them in one way or another will not close form1.
(Unless we change project type to something other than windows forms application)

The one I think is easiest to your situation is to create 3 forms:

  • form1 - will remain invisible and act as a manager, you can assign it to handle a tray icon if you want.

  • form2 - will have the button, which when clicked will close form2 and will open form3

  • form3 - will have the role of the other form that need to be opened.

And here is a sample code to accomplish that:
(I also added an example to close the app from 3rd form)

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1()); //set the only message pump to form1.
    }
}


public partial class Form1 : Form
{
    public static Form1 Form1Instance;

    public Form1()
    {
        //Everyone eveywhere in the app should know me as Form1.Form1Instance
        Form1Instance = this;

        //Make sure I am kept hidden
        WindowState = FormWindowState.Minimized;
        ShowInTaskbar = false;
        Visible = false;

        InitializeComponent();
        
        //Open a managed form - the one the user sees..
        var form2 = new Form2();
        form2.Show();
    }

}

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var form3 = new Form3(); //create an instance of form 3
        Hide();             //hide me (form2)
        form3.Show();       //show form3
        Close();            //close me (form2), since form1 is the message loop - no problem.
    }
}

public partial class Form3 : Form
{
    public Form3()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form1.Form1Instance.Close(); //the user want to exit the app - let's close form1.
    }
}


Note: working with panels or loading user-controls dynamically is more academic and preferable as industry production standards - but it seems to me you just trying to reason with how things work - for that purpose this example is better.

And now that the principles are understood let's try it with just two forms:

  • The first form will take the role of the manager just like in the previous example but will also present the first screen - so it will not be closed just hidden.

  • The second form will take the role of showing the next screen and by clicking a button will close the application.


    public partial class Form1 : Form
    {
        public static Form1 Form1Instance;

        public Form1()
        {
            //Everyone eveywhere in the app show know me as Form1.Form1Instance
            Form1Instance = this;
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Make sure I am kept hidden
            WindowState = FormWindowState.Minimized;
            ShowInTaskbar = false;
            Visible = false;

            //Open another form 
            var form2 = new Form2
            {
                //since we open it from a minimezed window - it will not be focused unless we put it as TopMost.
                TopMost = true
            };
            form2.Show();
            //now that that it is topmost and shown - we want to set its behavior to be normal window again.
            form2.TopMost = false; 
        }
    }
    
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            Form1.Form1Instance.Close();
        }
    }

If you alter the previous example - delete form3 from the project.

Good Luck.

Solution 5 - C#

You weren't specific, but it looks like you were trying to do what I do in my Win Forms apps: start with a Login form, then after successful login, close that form and put focus on a Main form. Here's how I do it:

  1. make frmMain the startup form; this is what my Program.cs looks like:

     [STAThread]
     static void Main()
     {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new frmMain());
     }
    
  2. in my frmLogin, create a public property that gets initialized to false and set to true only if a successful login occurs:

     public bool IsLoggedIn { get; set; }
    
  3. my frmMain looks like this:

     private void frmMain_Load(object sender, EventArgs e)
     {
         frmLogin frm = new frmLogin();
         frm.IsLoggedIn = false;
         frm.ShowDialog();
    
         if (!frm.IsLoggedIn)
         {
             this.Close();
             Application.Exit();
             return;
         }
    

No successful login? Exit the application. Otherwise, carry on with frmMain. Since it's the startup form, when it closes, the application ends.

Solution 6 - C#

use this code snippet in your form1.

public static void ThreadProc()
{
Application.Run(new Form());
}

private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
t.Start();
this.Close();
}

I got this from here

Solution 7 - C#

If you have two forms: frm_form1 and frm_form2 .The following code is use to open frm_form2 and close frm_form1.(For windows form application)

        this.Hide();//Hide the 'current' form, i.e frm_form1 
        //show another form ( frm_form2 )   
        frm_form2 frm = new frm_form2();
        frm.ShowDialog();
        //Close the form.(frm_form1)
        this.Close();

Solution 8 - C#

I usually do this to switch back and forth between forms.

Firstly, in Program file I keep ApplicationContext and add a helper SwitchMainForm method.

	    static class Program
{
    public static ApplicationContext AppContext { get;  set; }

	
	static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        //Save app context
        Program.AppContext = new ApplicationContext(new LoginForm());
        Application.Run(AppContext);
    }
	
	//helper method to switch forms
	  public static void SwitchMainForm(Form newForm)
    {
        var oldMainForm = AppContext.MainForm;
        AppContext.MainForm = newForm;
        oldMainForm?.Close();
        newForm.Show();
    }

	
}

Then anywhere in the code now I call SwitchMainForm method to switch easily to the new form.

// switch to some other form
var otherForm = new MyForm();
Program.SwitchMainForm(otherForm);

Solution 9 - C#

private void buttonNextForm(object sender, EventArgs e)
{
    NextForm nf = new NextForm();//Object of the form that you want to open
    this.hide();//Hide cirrent form.
    nf.ShowModel();//Display the next form window
    this.Close();//While closing the NextForm, control will come again and will close this form as well
}

Solution 10 - C#

//if Form1 is old form and Form2 is the current form which we want to open, then
{
Form2 f2 = new Form1();

this.Hide();// To hide old form i.e Form1
f2.Show();
}

Solution 11 - C#

This code may help you:

Master frm = new Master();

this.Hide();

frm.ShowDialog();

this.Close();

Solution 12 - C#

                     this.Visible = false;
                        //or                         // will make LOgin Form invisivble
                        //this.Enabled = false;
                         //  or
                       // this.Hide(); 

                                                    
                        
                        Form1 form1 = new Form1();
                        form1.ShowDialog();

                        this.Dispose();

Solution 13 - C#

I think this is much easier :)

    private void btnLogin_Click(object sender, EventArgs e)
    {
        //this.Hide();
        //var mm = new MainMenu();
        //mm.FormClosed += (s, args) => this.Close();
        //mm.Show();

        this.Hide();
        MainMenu mm = new MainMenu();
        mm.Show();
        
    }

Solution 14 - C#

Everyone needs to participate in this topic :). I want to too! I used WPF (Windows Presentation Foundation) to close and open windows. How I did:

  1. I used clean code, so I deleted App.xaml and create Program.cs
  2. Next, a window manager was created
  3. The program analyzes the keys and the manager can launch either 1 window or 2 windows (1 informational, then when the button is pressed, it closes and a new main window 2 opens)
internal class Program
{
	[STAThread]
	public static void Main(string[] args)
	{
		Mgm mgm = new Mgm(args);
		mgm.SecondaryMain();
	}
}

internal class Mgm
{
	private Dictionary<string, string> argsDict = new Dictionary<string, string>();

	private InformWindow iw = null;
	private MainWindow mw = null;
	private Application app = null;

	public Mgm(string[] args)
	{
		CheckInputArgs(args);
	}

	private void CheckInputArgs(string[] strArray)
	{
		if (strArray.Length == 0)
			return;

		for (int i = 0; i < strArray.Length; i++)
		{
			if (strArray[i].StartsWith("-") && !argsDict.ContainsKey(strArray[i]))
				argsDict.Add(strArray[i], null);
			else
				if (i > 0 && strArray[i - 1].StartsWith("-"))
					argsDict[strArray[i - 1]] = strArray[i];
		}
	}

	public void SecondaryMain()
	{
		if (!argsDict.ContainsKey("-f"))
			return;

		if (argsDict.ContainsKey("-i"))
		{
			if (String.IsNullOrEmpty(argsDict["-i"]) || !int.TryParse(argsDict["-i"], out _))
				iw = new InformWindow();
			else
				iw = new InformWindow(int.Parse(argsDict["-i"]));
			iw.PleaseStartVideo += StartMainWindow;
			app = new Application();
			app.Run(iw);
		}
		else
		{
			app = new Application();
			mw = new MainWindow(argsDict["-f"]);
			app.Run(mw);
		}
	}

	private void StartMainWindow(object o, EventArgs e)
	{
		mw = new MainWindow(argsDict["-f"]);
		app.MainWindow = mw;
		app.MainWindow.Show();
		iw.Close();
	}
}

The most important thing in this matter is not to get confused with the system.windows.application class

Solution 15 - C#

Suppose you have two Form, First Form Name is Form1 and second form name is Form2.You have to jump from Form1 to Form2 enter code here. Write code like following:

On Form1 I have one button named Button1, and on its click option write below code:

protected void Button1_Click(Object sender,EventArgs e)
{
    Form frm=new Form2();// I have created object of Form2
    frm.Show();
    this.Visible=false;
    this.Hide();
    this.Close();
    this.Dispose();
}

Hope this code will help you

Solution 16 - C#

I would solve it by doing:

private void button1_Click(object sender, EventArgs e)
{
    Form2 m = new Form2();
    m.Show();
    Form1 f = new Form1();
    this.Visible = false;
    this.Hide();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiontnhan07View Question on Stackoverflow
Solution 1 - C#nihiqueView Answer on Stackoverflow
Solution 2 - C#ManuzorView Answer on Stackoverflow
Solution 3 - C#MontDeskaView Answer on Stackoverflow
Solution 4 - C#G.YView Answer on Stackoverflow
Solution 5 - C#Barry NovakView Answer on Stackoverflow
Solution 6 - C#lakshmanView Answer on Stackoverflow
Solution 7 - C#maneeshView Answer on Stackoverflow
Solution 8 - C#Namig HajiyevView Answer on Stackoverflow
Solution 9 - C#Prateek ShuklaView Answer on Stackoverflow
Solution 10 - C#user2186819View Answer on Stackoverflow
Solution 11 - C#Jaydeo Kumar DharpureView Answer on Stackoverflow
Solution 12 - C#Aamir ZargarView Answer on Stackoverflow
Solution 13 - C#Sachith WickramaarachchiView Answer on Stackoverflow
Solution 14 - C#KULView Answer on Stackoverflow
Solution 15 - C#ShahnawazView Answer on Stackoverflow
Solution 16 - C#PolashView Answer on Stackoverflow