简体   繁体   中英

Close another form to C#

I have 2 windows form, 1 login form and 1 main form. I want to close main form and login form together. How can i do?

I tryed this command;

Form2 ac = new Form2();
ac.Show();
this.Close();

but this closing all forms. I want only close Form1 .

如果您关闭主窗体,当然所有窗口都会关闭,主窗体包含所有其他窗体,您的Q值不清楚,能否给我们一个清晰的代码段,以显示您要执行的操作?

If your Main method contains:

  Application.Run(form1);

And you are closing form1 , your application closes.

You could "temporary" hide the form1 while displaying the ac. Use ShowDialog, to block your code until the ac form is closed:

   using (Form2 ac = new Form2()) {
     this.Hide();
     if (ac.ShowDialog() == DialogResult.OK) {
       this.Show();
     } else {
      // Exit app
       this.Close();   
     }
   }

Depending on which form is calling which other form (and how), you have to somehow "bubble" the request to close from within the login form to the main form.

Suppose that form 1 calls form 2 modally:

public partial class Form1 : Form
{
    // ...

    private void callForm2()
    {
        var form2 = new Form2();
        if ( form2.ShowDialog( this )== DialogResult.Abort )
        {
            // Close myself if called form instructs me to close.
            Close();
        }
    }
}

As you see, I used the DialogResult.Abort as the "communication signal" to close. This could be done in Form2 like the following:

public partial class Form2 : Form
{
    // ...

    private void buttonCloseAll_Click( object sender, EventArgs args )
    {
        // Close myself _and_ return the abort result to the caller.
        DialogResult = DialogResult.Abort;
    }
}

Please note that this is just an (uncomplete example). I'm sure there are alternative solutions to your requirement.

The 1. form you open is the main form for the application. This has nothing to do how you name your forms or what is on this forms. If you close the main form your application terminates.

You could do this two things in your situation:

  1. hide your login form instead of closing it
  2. open your main form first and use your login form as a modal dialog on top of it. In this case you can close the login form and your applications continuous to run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM