Reputation:
I'm currently working on a simple notepad. What I want to happen is that when the user clicks on the "New" button that the form that is open closes and a new form opens. This is what I already have:
DialogResult newdialogresult = MessageBox.Show("Are you sure you want to create a new file and close the existing one?", "Simple Notepad", MessageBoxButtons.YesNo);
if(newdialogresult == DialogResult.Yes)
{
Form1 f1 = new Form1();
f1.ShowDialog();
this.Close();
}
The new form opens but the old one doesn't close.
Upvotes: 0
Views: 5765
Reputation: 59
I would just like to add another option for anyone who is interested.
In the Program.cs file you should see something like:
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
This simply starts the main thread and makes the specified form visible. The problem with this is that when you run "this.Close()" is will also terminate the main thread, so any form you are trying to open will close too.
You can do as the others suggest with "this.Hide()", however this doesn't release the resources that the current form is consuming. So what I like to do, in the Program.cs file, is this:
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var frm = new Form1();
frm.Show();
Application.Run();
}
}
This allows the main thread to continue even if the current form is closed. You do have to be careful though and end the main thread when you want to end the program. You can do this in the "FormClosed" event by calling "Application.Exit()".
Upvotes: 1
Reputation: 6577
The proper way to do it is to hide the main form, I agree with that. But you'd probably want to close main form when closing the child form sooner or later. To do that, you should close your main form when child form FormClosing
event is triggered. Try with this:
Form2 form = new Form2();
form.Show();
form.FormClosing += (obj, args) => { this.Close(); };
this.Hide();
Upvotes: 1
Reputation: 9759
Agree with David's answer, and adding to that, if you want this behavior, you can use the following code snippet insted -
DialogResult newdialogresult = MessageBox.Show("Are you sure you want to create a new file and close the existing one?", "Simple Notepad", MessageBoxButtons.YesNo);
if (newdialogresult == DialogResult.Yes)
{
Form2 f1 = new Form2();
f1.Show();
this.Hide();
}
Upvotes: 0
Reputation: 34573
If you step through the code you'll see that the this.Close();
doesn't get executed until you manually close the new window.
The ShowDialog method is used for showing a modal dialog box. Because of this, it does not return until the window is closed.
Depending on what else you want to do, you can either change the order of the Close/ShowDialog or change it to just Show
instead or Hide
the first form instead.
Upvotes: 0