简体   繁体   中英

C#: Close and Open two forms from a separate form

I have 3 forms. How can I make it so that one form is shown with .Show() and the other is hidden with .Hide() from a separate form?

This is part of my code

    private void buttonYes_Click(object sender, EventArgs e)
    {
        LoggedIn loggedinform = new LoggedIn();
        loggedinform.Hide(); // Hides another form that is in the background
        MainForm mainform = new MainForm();
        mainform.Show(); // Show first form
        this.Hide(); // Hides current form
    }

One problem, the LoggedIn form does not hide itself. From the looks of it it skips it and just goes for the mainform.Show();

Is this a bug or do I need to do something else?

The line LoggedIn loggedinform = new LoggedIn() is going to create a new instance of that login window. That might be useful if, say, you intended to show 5 "Login" windows onscreen all at once. I think what you want to do is retrieve a reference to the login window that is already showing, and hide that; so, avoid creating a new one.

Properly passing references to existing objects around the program is kind of a structural problem, and one that I ran into quite a bit in my early programming days. The quick, unclean, and generally not-recommended way is to declare instances of those singular objects (like, maybe, your login window) as static , so they can be retrieved anywhere. However, to fully answer your question in the best way, maybe you could describe the structure of your program a bit more (full code isn't necessary, just generally-speaking, what the flow is between classes)

Ok I figured it out. I can use

        Application.OpenForms[1].Hide();

[1] is the form I'm trying to hide. And it worked.

I also realized thanks to Katana that it makes sense why it wasn't working because it was basically making a new instance of the form instead of finding the current one. Sorry that my code is a mess.

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