Close two form by one click?

2019-07-27 11:44发布

I'm working on project with sign in feature

When I run the project there is a form (form1) run the sign in . after i click on login button build another form (form2) - It's the form of my program . and made the first form (form1) hide .

The problem is when I press at the X button in form2 it's close but the form1 it's still running .

I tried to close the form1 instead of hide ... but this will close form2 before launching

In form1:

this.Hide();
Form2 x = new Form2();                 
x.Show();

标签: c# forms
4条回答
劳资没心,怎么记你
2楼-- · 2019-07-27 12:16

I think you have your forms around the wrong way.

Form1 sould be your app and shold show Form2 as a dialog when it first loads, then when it closes you can process the result and decide wether to continue or close the application.

Something like:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Load += new EventHandler(Form1_Load);
    }

    void Form1_Load(object sender, EventArgs e)
    {
        Form2 myDialog = new Form2();
        if (myDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
        {
            // failed login
            // exit application
        }
        // all good, continue
    }
}
查看更多
男人必须洒脱
3楼-- · 2019-07-27 12:22

You go to your form2 then in the event of the form look for FormClosed.

Put this code in your eventhandler:

private void Form2_FormClosed(object sender, FormClosedEventArgs e)
    {
        Application.Exit();
    }

FormClosed is the event whenever the user closes the form. So when you close the form put a code that will exit your application that is -applicationn.exit();-

Hope this will work.

查看更多
成全新的幸福
4楼-- · 2019-07-27 12:27

try this, in the log in button if access is granted

private void logInBtn_Click(object sender, EventArgs e)
        {
            Form2 frm = new Form2();
            frm.ShowDialog();
            this.Hide();
        }

then in form2 if you want to exit

private void exitBtn_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

hope this helps.

查看更多
SAY GOODBYE
5楼-- · 2019-07-27 12:40

You could subscribe to the child forms FormClosed event and use that to call Close on the parent form.

x.FormClosed += new FormClosedEventHandler(x_FormClosed);

void x_FormClosed(object sender, FormClosedEventArgs e)
{
    this.Close();
}
查看更多
登录 后发表回答