Closing previous form box in C++ .net

2.8k Views Asked by At

I am using Visual C++ 2005 and I am creating an application that has various forms. What I am wanting to happen is when a new form is opened the previous one is closed. I'm sure it's just one line of code that I need to add but being new to this I have no idea what that is. The form I want to close is Form1.h. Any help would be much appreciated.

Here is my current code:

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
                 Parts ^parts = gcnew Parts();
                 parts->ShowDialog();
                 this->Close();
3

There are 3 best solutions below

6
On

You can do that by simply calling the Close() method from the form you wish to close. Have you tried that?

0
On

I'm not sure how it is in C++ but in C# you can do it like this

static Programm
{
    static bool run = true;
    static int state = 1;
    /// <summary>
    /// Der Haupteinstiegspunkt für die Anwendung.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        while (run)
        {
            Application.Run(getForm());
        }
    }

    static private Form getForm()
    {
        Form ret = null;

        switch (state)
        {
            case 1:
                ret = new Form1();
                break;
            case 2:
                ret = new Form2();
                break;
        }

        return ret;
    }

    static public void setState(int i)
    {
        if (i == 0)
        {
            run = false;
        }
        else
        {
            state = i;
        }
    }
}

Hope this helps

0
On

In order to show the second form (Parts), you must use Show instead of ShowDialog. ShowDialog block the execution and the Close method won't be called until the form Parts is closed.

Parts ^parts = gcnew Parts();
parts->Show(); // Show the form and continue execution
this->Close();

But keep one thing in mind, if the caller form is the main window of application, when the method Close is called the whole application will be closed, and with it the form Parts will be closed too. To work around this behaviour, i would start the application with a invisible form. When that form is loaded, then your "caller" form will be started.