简体   繁体   中英

Showing/Hiding the main form in C#

I am working on a program where clicking on a button on form1 will open form2. I will then hide form1 until form2 is closed. The problem I have is that I cannot get form1 to show after form2 closes. Any ideas on how to fix this?

        try
        {
            Form1.ActiveForm.Hide();
            AddGradeForm = new Form2(Form.NumberOfSelections);
            AddGradeForm.ShowDialog();
            MessageBox.Show(AddGradeForm.Result.ToString());
        }
        catch (Exception i)
        {
            Form1.ActiveForm.Hide();
            AddGradeForm.Dispose();
            AddGradeForm = new Form2(Form.NumberOfSelections);
            AddGradeForm.ShowDialog();
            MessageBox.Show(AddGradeForm.Result.ToString());
        }
        Form1.ActiveForm.Show();

ERROR: NullReferenceException was unhanded. Object reference not set to an instance of an object.

That's because there is no active form anymore, you've hidden the one that could be active. This has other side effects, your app will lose the focus. What you need to do is keep track of the previously active form and get it to show again before the dialog closes. Like this:

        var prior = Form.ActiveForm;
        using (var dlg = new Form2()) {
            dlg.FormClosing += delegate { prior.Show(); };
            prior.Hide();
            if (dlg.ShowDialog() == DialogResult.OK) {
                MessageBox.Show("result");
            }
        }

最后一行应该是:

Form1.Show();

The line

Form1.ActiveForm.Show();

should be

Form1.Show();

Also note that it may not be called if there's an exception. wrap it in a finally block if you want it to be called.

    try
    {
        Form1.ActiveForm.Hide();
        // ...
    }
    catch (Exception i)
    {
        // ...
    }
    finally
    {
        Form1.Show();
    }

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