c# open a new form then close the current form?
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();
}
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());
}
}
}
Try to do this...
{
this.Hide();
Form1 sistema = new Form1();
sistema.ShowDialog();
this.Close();
}
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.
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:
-
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()); }
-
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; }
-
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.