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();
}
}
This question is related to
c#
winforms
user-interface
To link to a form you need:
Form2 form2 = new Form2();
form2.show();
this.hide();
then hide the previous form
private void button5_Click(object sender, EventArgs e)
{
this.Visible = false;
Form2 login = new Form2();
login.ShowDialog();
}
i believe the following code will only run after form1
is closed
while (true)
{
if (form1.Visible == false)
form2.Show();
}
Why not start your form2
from form1
instead?
Form2 form2 = new Form2();
private void button1_Click_1(object sender, EventArgs e)
{
if (richTextBox1.Text != null)
{
form1.Visible=false;
form2.Show();
}
else MessageBox.Show("Insert Attributes First !");
}
Anything after Application.Run( ) will only be executed when the main form closes.
What you could do is handle the VisibleChanged
event as follows:
static Form1 form1;
static Form2 form2;
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
form2 = new Form2();
form1 = new Form1();
form2.Hide();
form1.VisibleChanged += OnForm1Changed;
Application.Run(form1);
}
static void OnForm1Changed( object sender, EventArgs args )
{
if ( !form1.Visible )
{
form2.Show( );
}
}
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();
}
}
Source: Stackoverflow.com