I am doing an application a Windows Form application. At first, a certain form appears, and after the user hits the next button, this form should be hidden and another form is shown.
I tried to do it. I managed to hide the current form, but the next one won't show.
Here is my attempt:
This is the button's event handler
private void button1_Click_1(object sender, EventArgs e)
{
if (richTextBox1.Text != null)
{
this.Visible=false;
}
else
MessageBox.Show("Insert Attributes First !");
}
This is the main function:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form2 form2 = new Form2();
Form1 form1 = new Form1();
form2.Hide();
Application.Run(form1);
while (true)
{
if (form1.Visible == false)
form2.Show();
}
}
The While statement will not execute until after form1 is closed - as it is outside the main message loop.
Remove it and change the first bit of code to:
private void button1_Click_1(object sender, EventArgs e)
{
if (richTextBox1.Text != null)
{
this.Visible=false;
Form2 form2 = new Form2();
form2.show();
}
else MessageBox.Show("Insert Attributes First !");
}
This is not the best way to achieve what you are looking to do though. Instead consider the Wizard design pattern.
Alternatively you could implement a custom ApplicationContext that handles the lifetime of both forms. An example to implement a splash screen is here, which should set you on the right path.
http://www.codeproject.com/KB/cs/applicationcontextsplash.aspx?display=Print
A) The main GUI thread will run endlessly on the call to Application.Run, so your while loop will never be reached
B) You would never want to have an endless loop like that (the while(true) loop) - it would simply freeze the thread. Not really sure what you're trying to achieve there.
I would create and show the "main" (initial) form in the Main method (as Visual Studio does for you by default). Then in your button handler, create the other form and show it as well as hiding the main form (not closing it). Then, ensure that the main form is shown again when that form is closed via an event. Example:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 otherForm = new Form2();
otherForm.FormClosed += new FormClosedEventHandler(otherForm_FormClosed);
this.Hide();
otherForm.Show();
}
void otherForm_FormClosed(object sender, FormClosedEventArgs e)
{
this.Show();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With