开发者

C# mainform showing when subform closes

开发者 https://www.devze.com 2023-03-19 04:33 出处:网络
I want to close my 2nd form and show my 1st form, without creating a new object. frmMain Mainfrm = new Mainfrm();

I want to close my 2nd form and show my 1st form, without creating a new object.

frmMain Mainfrm = new Mainfrm();
Mainfrm.Show();
this.Close();

On my main form there is special coding for certain users of the program, and by creating a new 开发者_如何学Goobject is tosses everything away that is mainly created when the mainfrm is first created on application launch.


Don't close your main form, hide it instead. Do this.Hide(); so it will not be visible to the user and your main form data will remain. You can call this.Show() to show it again without creating a new instance.


Have you considered showing the 2nd form as a dialog?

From the main form:

new Form2().ShowDialog();

This causes the main form to remain open, but the user is unable to access it until it closes then 2nd form.


in the main form

    private void button1_Click(object sender, EventArgs e) // to open form2
    {
        Form2 frm2 = new Form2(this);
        frm2.Show();
        this.Hide();
    }

in the form2

private mainForm mainForm; //mainForm is the name of the Main form
    public Form2(mainForm mainForm) 
    {
        InitializeComponent();
        this.mainForm = mainForm;
    }

    private void button1_Click(object sender, EventArgs e)// to close form2 and show main
    {
        this.mainForm.Show();
        this.Close();
    }


You should be able to instantiate another Windows Form in the same way. Make it modal or modeless and you should be fine. You won't lose the information from your other form.

See here for the MSDN article on Dialog Boxes.


Do you want the main form to hide while the second is open? Or just make sure it is still there.

In the normal course of events, a form created in another form create a type of parent child relationship, so you should automatically see the first form when the second closes. Having the data reflected in the first form requires getting the data back, which can be done via setting up event handlers.

The exception is if you close the main form, which can be avoided by hiding it instead and then unhiding it when #2 is finished.


If you are using Visual Studio, it probably put Application.Run (new Form1()) in your static void Main(). That causes the application to exit when Form1 closes (so that's why Form2 doesn't stick around.)

Instead you can use Application.Run() (without parameters) and call Application.Exit explicitly when you want to end the program.

0

精彩评论

暂无评论...
验证码 换一张
取 消