Calling a form and closing a form in the same event

Asked

Viewed 38,715 times

1

How do I call one form and close a form at the same event. For example:

private void iniciar_Click(object sender, EventArgs e)
{
    Close();
    Frm1 newForm2 = new Frm1();
    newForm2.ShowDialog();  
}
  • just to say q : I put Close(); on the last line and n came up empty... the first form remains open

5 answers

6


This is done by placing the second form in a Thread:

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

private void iniciar_Click(object sender, EventArgs e)
{
    System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
    t.SetApartmentState(ApartmentState.STA);
    t.IsBackground = true;
    t.Start();
    this.Close();
}
  • 2

    Before starting the new thread, it would not be better to ensure that the appartment state is STA (calling t.SetAppartmentState(ApartmentState.STA)? And define t.IsBackground = true so that the process doesn’t end when closing the previous main form? It’s been a long time since I’ve done things like this...

  • 1

    I made it as simple as possible, but you’re right. I’ll update the answer. Thanks!

2

Hello, I was having the same problem that our colleague @Andersonbp mentioned, there searching on the internet, I found a reply from @Juniortunjr that was easier to understand and solved my problem.

    private void btnIniciar_Click(object sender, EventArgs e)
    {
        this.Hide();
        Form f = new frm2();
        f.Closed += (s, args) => this.Close(); 
        f.Show();
    }

0

It gave error a few times, but I calmly managed to execute:

private void btnIniciar_Click(object sender, EventArgs e)
    {
        this.Hide();
        Form f = new frm2();
        f.Closed += (s, args) => this.Close(); 
        f.Show();
    }

The copy and paste structure is as follows:

this. Hide(); [star_form] frm = new star_form, frm. Closed += (s, args) => this. Close(); frm. Show();

Whatever is between [] (square brackets), put the name of the form you want to call. For example:

    private void voltarToolStripMenuItem_Click(object sender, EventArgs e)
    {
        this.Hide();
        frm_Menu frm = new frm_Menu();
        frm.Closed += (s, args) => this.Close();
        frm.Show();
    }

With this we can go back to a previous window or to another, understood? Thank you very friend Danillo Victtor!

0

Use the line this. Hide(); to close your LOGIN screen, as in the example below.

private void iniciar_Click(object sender, EventArgs e)

{

Frm1 newForm2 = new Frm1();
this.Hide(); // use dessa maneira.
newForm2.ShowDialog();  

}

-1

try this on mine worked

Visible = false;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.