Opening a new form, closing an old C #

I'm new to C #, and I'm doing it on my own, trying to make a program with many features to teach myself how to work with C #. I usually look on the Internet if I don't know anything, but it drove me crazy.

I remember at the very beginning I started this, that I wanted to open the form and close the old one, but when I closed the new form, the old form will appear again and other strange varieties of this problem. this.Hide () didn't do anything either.

I am currently using this code to open a new form, but it looks like there should be something with 1 line of code for something simple, like opening a form ... My question is, is there.

    private void OpenMainForm()
    {
        MainForm frm2 = new MainForm();
        frm2.FormClosed += new FormClosedEventHandler(frm2_FormClosed);
        frm2.Show();

        // Since this.Hide() for some reason doesn't work, i'll have to do this crap
        this.WindowState = FormWindowState.Minimized;
        this.ShowInTaskbar = false;
    }

    private void frm2_FormClosed(object sender, FormClosedEventArgs e)
    {
        this.Close();
    }
+5
source share
4

, , ShowDialog(). form_closed event.

:

private void OpenMainForm()
{
    MainForm frm2 = new MainForm();
    this.Hide();           //Hide the main form before showing the secondary
    frm2.ShowDialog();     //Show secondary form, code execution stop until frm2 is closed
    this.Show();           //When frm2 is closed, continue with the code (show main form)
}
+13

:

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

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();
 }
+4

This works great for me.

Form2 frm = new Form2();
frm.Show();
frm.Activate();
this.Hide();

but if you want to close the entire application from Form2 ... you must add Application.Exit();to the FormClosingform2 event

+2
source

You can hide the old shape as shown below.

private void frm2_FormClosed(object sender, FormClosedEventArgs e)
{
    this.Hide();
}
0
source

All Articles